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

Chris Liechti cliechti at gmx.net
Wed Jul 24 08:47:10 EDT 2002


"Gerard A.W. Vreeswijk" <gv at cs.uu.nl> wrote in
news:3D3E9F34.90FB8B3F at cs.uu.nl: 

> 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 <cliechti at gmx.net>




More information about the Python-list mailing list