Wrapper functions and arguments

Ryan Ginstrom software at ginstrom.com
Tue Oct 2 02:35:53 EDT 2007


> On Behalf Of Jeremy Sanders
> def a(x, y, z):
>   print x, y, z
> def b(x, y, z='fruitbat')
>   print x, y, z
> 
> for func in a, b:
>   def wrapper(func=func, *args, **argsk):
>      # do something
>      func(*args, **argsk)
>   x.append(wrapper)
> 
> x[0](1, 2, 3)
> x[1](1, 2)
> ...
> 
> Is there any way to do this? Can you capture arguments in a 
> tuple and dict, but still receive other keyword arguments? 

I think you're missing one level of wrapping.

>>> def a(x, y, z):
	print x, y, z

>>> def b(x, y, z='fruitbat'):
	print x, y, z

>>> x = []
>>> for func in a, b:
	def wrapper(func):
		def wrapped(*args, **kwds):
			print "wrapped!"
			func(*args, **kwds)
		return wrapped
	x.append(wrapper(func))
	
>>> x[0](1, 2, 3)
wrapped!
1 2 3
>>> x[1](1, 2)
wrapped!
1 2 fruitbat
>>> 

---
Regards,
Ryan Ginstrom




More information about the Python-list mailing list