471,355 Members | 2,037 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,355 software developers and data experts.

Wrapper functions and arguments

One little issue I have is to write a little wrapper which can generally
pass standard and keyword arguments to a callee:

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? The only solution I found was to
implement wrapper as a class (like I would in c++):

class wrapper(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **argsk):
self.func(*args, **argsk)

Jeremy

--
Jeremy Sanders
http://www.jeremysanders.net/
Oct 2 '07 #1
1 1188
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

Oct 2 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.