Wrapper functions and arguments

J

Jeremy Sanders

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
 
R

Ryan Ginstrom

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.
print x, y, z
print x, y, z
def wrapper(func):
def wrapped(*args, **kwds):
print "wrapped!"
func(*args, **kwds)
return wrapped
x.append(wrapper(func))
wrapped!
1 2 3
wrapped!
1 2 fruitbat
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top