如何在装饰器中使用命名参数?

时间:2009-03-09 18:37:21

标签: python language-features decorator

如果我有以下功能:


def intercept(func):
  # do something here

@intercept(arg1=20)
def whatever(arg1,arg2):
  # do something here

我希望拦截仅在 arg1 为20时启动。我希望能够将命名参数传递给该函数。我怎么能做到这一点?

这是一个小代码示例:



def intercept(func):
    def intercepting_func(*args,**kargs):
        print "whatever"
        return func(*args,**kargs)
    return intercepting_func

@intercept(a="g")
def test(a,b):
    print "test with %s %s" %(a,b)

test("g","d")

抛出以下异常TypeError:intercept()得到一个意外的关键字参数'a'

3 个答案:

答案 0 :(得分:15)

请记住

@foo
def bar():
    pass

相当于:

def bar():
    pass
bar = foo(bar)

所以,如果你这样做:

@foo(x=3)
def bar():
    pass

相当于:

def bar():
    pass
bar = foo(x=3)(bar)

所以你的装饰师需要看起来像这样:

def foo(x=1):
    def wrap(f):
        def f_foo(*args, **kw):
            # do something to f
            return f(*args, **kw)
        return f_foo
    return wrap

换句话说,def wrap(f)实际上是装饰器,foo(x=3)是一个返回装饰器的函数调用。

答案 1 :(得分:11)

from functools import wraps

def intercept(target,**trigger):
    def decorator(func):
        names = getattr(func,'_names',None)
        if names is None:
            code = func.func_code
            names = code.co_varnames[:code.co_argcount]
        @wraps(func)
        def decorated(*args,**kwargs):
            all_args = kwargs.copy()
            for n,v in zip(names,args):
                all_args[n] = v
            for k,v in trigger.iteritems():
                if k in all_args and all_args[k] != v:
                    break
            else:
                return target(all_args)
            return func(*args,**kwargs)
        decorated._names = names
        return decorated
    return decorator

示例:

def interceptor1(kwargs):
    print 'Intercepted by #1!'

def interceptor2(kwargs):
    print 'Intercepted by #2!'

def interceptor3(kwargs):
    print 'Intercepted by #3!'

@intercept(interceptor1,arg1=20,arg2=5) # if arg1 == 20 and arg2 == 5
@intercept(interceptor2,arg1=20)        # elif arg1 == 20
@intercept(interceptor3,arg2=5)         # elif arg2 == 5
def foo(arg1,arg2):
    return arg1+arg2

>>> foo(3,4)
7
>>> foo(20,4)
Intercepted by #2!
>>> foo(3,5)
Intercepted by #3!
>>> foo(20,5)
Intercepted by #1!
>>>

functools.wraps执行wiki上的“简单装饰器”;更新__doc____name__和装饰器的其他属性。

答案 2 :(得分:3)

你可以在装饰器中使用* args和** kwargs:

def intercept(func, *dargs, **dkwargs):
    def intercepting_func(*args, **kwargs):
        if (<some condition on dargs, dkwargs, args and kwargs>):
            print 'I intercepted you.'
        return func(*args, **kwargs)
    return intercepting_func

由您决定如何传递参数以控制装饰器的行为。

为了使最终用户尽可能透明,您可以使用Python wiki或Michele Simionato "decorator decorator"

上的“简单装饰器”