装饰器,用于转换函数的参数 [英] A decorator to convert arguments of a function
本文介绍了装饰器,用于转换函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用装饰器来转换函数的参数.
I'd like to use a decorator to convert arguments of a function.
所以不要这样做:
def get_data(dt, symbol, depth, session):
dt = to_date(dt)
...
或
def get_data(dt, symbol, depth, session):
dt = convert(dt, to_date)
...
我希望能够写类似的东西
I would like to be able to write something like
@convert('dt', to_date)
def get_data(dt, symbol, depth, session):
...
但是我对此功能不太满意.
but I don't feel very confortable with this feature.
如何编写这样的装饰器?
How to write such a decorator ?
推荐答案
稍微弄弄它,并学到了很多有关生成器的知识:
Fiddled around with it a bit and learned quite a bit about generators:
def convert(arg, mod):
def actual_convert(fn):
if arg not in fn.__code__.co_varnames:
return fn
else:
def new_function(*args, **kwargs):
l_args = list(args)
index = fn.__code__.co_varnames.index(arg)
l_args[index] = mod(l_args[fn.__code__.co_varnames.index(arg)])
args = tuple(l_args)
return fn(*args, **kwargs)
return new_function
return actual_convert
@convert('x',lambda x: x+1)
def add(x,y):
return x + y
print("Should be 5:",add(3,1))
这目前仅适用于普通参数,不适用于关键字参数.不过,这样做也很容易.
This will only work with normal arguments for now, not keyword arguments. It would be fairly easy to do that, too, though.
这篇关于装饰器,用于转换函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文