How do I write a wrapper that prepend and append code based on arguments.. Here is the original method :
def method(self, arg1, arg2, arg3, ret='abc'):
arg1 = pre_fun(arg1)
rv = None
..... code ....
if ret == 'abc' : return abc_fun(rv)
if ret == 'efg' : return efg_fun(rv)
want to convert it to something along the line :
@pre(fun=pre_fun, arg='arg1')
@post(ret1=abc_fun, arg_ret1='rv', ret2=efg_fun, arg_ret2='rv')
def method(self, arg1, arg2, arg3, ret='abc'):
rv = None
....... code .....
I know it is not exactly like this. Is it possible. Also can I have defaults, so that I can say :
@pre
@post
def method(self, arg1, arg2, arg3, ret='abc'):
rv = None
....... code .....
OR if not I'm OK in hard-coding the parameters from the get go. (I would even prefer it for shortness.May be even @pre_post )
I think my arg_xxx='rv' is a bit flaky , but cant figure other way.
my work in progress, not tested yet :
def pp(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
args[0] = xbitx(args[0])
fun(*args, **kwargs)
if ret == 'numpy' : return args[0]
return iSDP(val=args[0], size=kwargs['size'], spaOnbits=kwargs['spaOnbits'])
return wrapper