我正在编写一个装饰器,需要在装饰它的函数调用之前调用其他函数。装饰的函数可能具有位置参数,但是装饰器将调用的函数只能接受关键字参数。有没有人可以方便地将位置参数转换为关键字参数?
I am writing a decorator that needs to call other functions prior to call of the function that it is decorating. The decorated function may have positional arguments, but the functions the decorator will call can only accept keyword arguments. Does anyone have a handy way of converting positional arguments into keyword arguments?
我知道我可以得到修饰函数的变量名列表:
I know that I can get a list of the variable names of the decorated function:
>>> def a(one, two=2): ... pass >>> a.func_code.co_varnames ('one', 'two')但是我可以
我的装饰器看起来像这样:
My decorator looks like this:
class mydec(object): def __init__(self, f, *args, **kwargs): self.f = f def __call__(self, *args, **kwargs): hozer(**kwargs) self.f(*args, **kwargs)除了比较kwargs和co_varnames,向kwargs添加任何不存在的东西,并希望达到最佳效果之外,还有其他方法吗?
Is there a way other than just comparing kwargs and co_varnames, adding to kwargs anything not in there, and hoping for the best?
推荐答案注意-co_varnames将包含局部变量以及关键字。这可能无关紧要,因为zip会截短较短的序列,但是如果您传递错误数量的args,则可能导致混乱的错误消息。
Note - co_varnames will include local variables as well as keywords. This probably won't matter, as zip truncates the shorter sequence, but may result in confusing error messages if you pass the wrong number of args.
func_code.co_varnames [:func_code.co_argcount] ,但最好使用检查模块。即:
You can avoid this with func_code.co_varnames[:func_code.co_argcount], but better is to use the inspect module. ie:
import inspect argnames, varargs, kwargs, defaults = inspect.getargspec(func)您可能还想处理函数定义 ** kwargs 或 * args (即使与装饰器一起使用时也会引发异常)。如果设置了这些,则 getargspec 的第二个和第三个结果将返回其变量名,否则将为None。
You may also want to handle the case where the function defines **kwargs or *args (even if just to raise an exception when used with the decorator). If these are set, the second and third result from getargspec will return their variable name, otherwise they will be None.
更多推荐
Python将args转换为kwargs
发布评论