Function wrapper a la Perl's Hook::WrapSub?

Gerard A.W. Vreeswijk gv at cs.uu.nl
Wed Jul 24 08:36:04 EDT 2002


Hi there,

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






More information about the Python-list mailing list