如果我有一个功能:
@aDecorator
def myfunc1():
# do something here
if __name__ = "__main__":
# this will call the function and will use the decorator @aDecorator
myfunc1()
# now I want the @aDecorator to be replaced with the decorator @otherDecorator
# so that when this code executes, the function no longer goes through
# @aDecorator, but instead through @otherDecorator. How can I do this?
myfunc1()
是否可以在运行时替换装饰器?
答案 0 :(得分:14)
正如Miya所提到的,在解释器获得该函数声明之前,您可以在任何点上用另一个函数替换装饰器。但是,一旦将装饰器应用于该函数,我认为没有办法用另一个动态替换装饰器。例如:
@aDecorator
def myfunc1():
pass
# Oops! I didn't want that decorator after all!
myfunc1 = bDecorator(myfunc1)
无效,因为myfunc1不再是您最初定义的功能;它已被包裹。这里最好的方法是手动应用装饰器,oldskool-style,即:
def myfunc1():
pass
myfunc2 = aDecorator(myfunc1)
myfunc3 = bDecorator(myfunc1)
编辑:或者,更清楚一点,
def _tempFunc():
pass
myfunc1 = aDecorator(_tempFunc)
myfunc1()
myfunc1 = bDecorator(_tempFunc)
myfunc1()
答案 1 :(得分:5)
我不知道是否有一种方法可以在应用装饰器后“替换”装饰器,但我想可能没有,因为该功能已经被更改。
无论如何,您可能会在运行时根据某些条件应用装饰器:
#!/usr/bin/env python
class PrintCallInfo:
def __init__(self,f):
self.f = f
def __call__(self,*args,**kwargs):
print "-->",self.f.__name__,args,kwargs
r = self.f(*args,**kwargs)
print "<--",self.f.__name__,"returned: ",r
return r
# the condition to modify the function...
some_condition=True
def my_decorator(f):
if (some_condition): # modify the function
return PrintCallInfo(f)
else: # leave it as it is
return f
@my_decorator
def foo():
print "foo"
@my_decorator
def bar(s):
print "hello",s
return s
@my_decorator
def foobar(x=1,y=2):
print x,y
return x + y
foo()
bar("world")
foobar(y=5)
答案 2 :(得分:3)
这是一个了不起的recipe to get you started。基本上,我们的想法是将类实例传递给装饰器。然后,您可以在类实例上设置属性(如果您愿意,可以将其设置为Borg)并使用它来控制装饰器本身的行为。
以下是一个例子:
class Foo:
def __init__(self, do_apply):
self.do_apply = do_apply
def dec(foo):
def wrap(f):
def func(*args, **kwargs):
if foo.do_apply:
# Do something!
pass
return f(*args, **kwargs)
return func
return wrap
foo = Foo(False)
@dec(foo)
def bar(x):
return x
bar('bar')
foo.do_apply = True
# Decorator now active!
bar('baz')
当然,您还可以合并“装饰器装饰器”以保留签名等。
答案 3 :(得分:1)
当然 - 您可以获取功能对象并随意执行任何操作:
# Bypass a decorator
import types
class decorator_test(object):
def __init__(self, f):
self.f = f
def __call__(self):
print "In decorator ... entering: ", self.f.__name__
self.f()
print "In decorator ... exiting: ", self.f.__name__
@decorator_test
def func1():
print "inside func1()"
print "\nCalling func1 with decorator..."
func1()
print "\nBypassing decorator..."
for value in func1.__dict__.values():
if isinstance(value, types.FunctionType) and value.func_name == "func1":
value.__call__()
答案 4 :(得分:0)
如果你想明确地改变装饰器,你也可以选择更明确的方法,而不是创建一个装饰函数:
deco1(myfunc1, arg1, arg2)
deco2(myfunc1, arg2, arg3)
deco1()和deco2()将应用装饰器提供的功能,并使用参数调用myfunc1()。
答案 5 :(得分:-1)
我知道这是一个老线程,但我很乐意这样做
def change_deco(name, deco, placeholder=' #'):
with open(name + '.py', 'r') as file:
lines = file.readlines()
for idx, string in enumerate(lines):
if placeholder in string and repr(placeholder) not in string:
lines[idx] = f' @{deco}\r\n'
exec(''.join(lines))
return locals()[name]
答案 6 :(得分:-2)
如果装饰器是一个函数,只需替换它。
aDecorator = otherDecorator