I very much would like to have a Hook::WrapSub (Perl) module for
Python. What does it do? Well, read
http://de-filippis.com/h/Hook-WrapSub-0.03.readme.shtml
:-) Or, if that one's dead,
http://cpan.lerner.co.il/modules/by-category/20_Control_Flow_Utilities/Hook/Hook-WrapSub-0.02.readme
In a nutshell, a subroutine (or function, or def) wrapper enables
intercepting a call to any named function; handlers may be added both
before and after the call to the intercepted function. My example:
==========================================================
#!/usr/bin/perl
use Hook::WrapSub qw( wrap_subs ); # import module
wrap_subs \&before, 'f', \&after; # execute 'before' before 'f' and
'after' after 'f'
sub f { # some pointless recursive function
my $arg = shift;
return 2*f($arg-1) if $arg > 0;
return 1
}
sub before {
print "Entering function $Hook::WrapSub::name with arguments @_\n";
}
sub after {
print "Exiting $Hook::WrapSub::name with result
@Hook::WrapSub::result\n";
}
f(5);
==========================================================
Outputs:
Entering function main::f with arguments 5
Entering function main::f with arguments 4
Entering function main::f with arguments 3
Entering function main::f with arguments 2
Entering function main::f with arguments 1
Entering function main::f with arguments 0
Exiting main::f with result 1
Exiting main::f with result 2
Exiting main::f with result 4
Exiting main::f with result 8
Exiting main::f with result 16
Exiting main::f with result
==========================================================
I know that there is this magnifient trace.py-module by Skip Montanaro
and Andrew Dalke but I don't have enough skills to rework that script
into a inline function hook (rather than as a standalone tracer, like
trace.py is)
Further, I suspect that a Python Hook::WrapDef can be distilled from
trace.py, but currently I do not have enough Python skills to figure out
how.
Anyone?
Thanks.
Gerard Vreeswijk
> Hi there,
>
> I very much would like to have a Hook::WrapSub (Perl) module for
> Python. What does it do? Well, read
is so simple that is not in a module <wink>:
>>> class Wrap:
... def __init__(self, callable, before=None, after=None):
... self.before = before
... self.after = after
... self.callable = callable
... def __call__(self, *args, **kwargs):
... if self.before is not None:
... self.before(args, kwargs)
... result = self.callable(*args, **kwargs)
... if self.after is not None:
... self.after(args, kwargs, result)
... return result
...
>>> def log(a, k):
... print "called with args:", a, k
...
>>> def result(a,k,r):
... print "result:", r
...
>>> def f(x):
... return x+1
...
>>> w = Wrap(f, log, result)
>>> w(27)
called with args: (27,) {}
result: 28
28
>>>
chris
--
Chris <clie...@gmx.net>
> is so simple that is not in a module <wink>:
Amazing that such a thing can be done in merely 12 (twelve) lines of
code. I've tried it and it works (of course), thanks to Python (I
guess) and Chris.
Gerard
Andreas