Tuesday, 10 September 2013

Decorating a function to add custom arguments to function

Decorating a function to add custom arguments to function

I am interested in creating a generic function and decorating all other
functions with it. The new function will contain arguments from both
functions. Example
def decorator(func):
Some chunk of code
@decorator
def func(a,b):
print a**2,b**2
return a**2,b**2
#Equivalent func of what I want out of the decorator
def equiv_func(a,b,var):
print var # I want to modify all decorated functions to accept a new
# argument and print it using "print var"
print a**2, b**2
return a**2, b**2
This is what I kind of came up with but...
def decor(func):
def modify(var,**kwargs):
print var
x,y=func(**kwargs)
return x,y
return modify
@decor
def func(a,b):
print a**2,b**2
return a**2,b**2
>>> func(var="hi",a=4,b=5)
hi
16 25
I used **kwargs as a way to account for arguments of func, but this forces
me to use func(var="hi",a=4,b=5) instead of func(a=4,b=5,var="hi") due to
the positioning of **kwargs.
Also, this work around prevents me from using **kwargs when defining my
decorator when I need it since it is already used to input arguments into
func.
I hope my question is clear. Thanks for any help in advance, coding gurus!

No comments:

Post a Comment