具有可选参数的函数的Decorator

时间:2014-09-17 12:10:56

标签: python python-2.7 decorator python-decorators

我有一个带有许多参数的函数my_f(其中一些可以是可选的),例如,

def my_f(a, b, opt_arg = 3):
    #do some stuff

现在我想为这个函数编写一些装饰器,它将根据可选参数opt_arg执行一些简单的操作。我不知道my_f的参数数量,但我知道可选参数的名称。我怎么能这样做?是否有可能以my_f(1,2, opt_arg=3)my_f(opt_arg =3, 1,2,3,4)变体正确的方式进行?

1 个答案:

答案 0 :(得分:1)

在装饰器包装器中使用**kw变量keywords参数,并查看其中是否存在opt_arg

from functools import wraps

def yourdecorator(f):
    @wraps(f)
    def wrapper(*args, **kw):
        opt_arg = kw.get('opt_arg')
        if opt_arg is not None:
            print "opt_arg was given and set to {!r}".format(opt_arg)
        return f(*args, **kw)
    return wrapper

演示:

>>> from functools import wraps
>>> def yourdecorator(f):
...     @wraps(f)
...     def wrapper(*args, **kw):
...         opt_arg = kw.get('opt_arg')
...         if opt_arg is not None:
...             print "opt_arg was given and set to {!r}".format(opt_arg)
...         return f(*args, **kw)
...     return wrapper
... 
>>> @yourdecorator
... def my_f(a, b, opt_arg=3):
...     pass
... 
>>> my_f(42, 81)
>>> my_f(42, 81, opt_arg=3.14)
opt_arg was given and set to 3.14