方法一:基本注册装饰器
我已经在这里回答了这个问题:Python中通过数组索引调用函数 https://stackoverflow.com/questions/5707589/calling-functions-by-array-index-in-python/5707605#5707605 =)
方法二:源码解析
如果您无法控制class定义,这是你想要假设的一种解释,这是不可能的(没有代码读取反射),因为例如装饰器可能是一个无操作装饰器(就像在我的链接示例中),它仅返回未修改的函数。 (尽管如此,如果您允许自己包装/重新定义装饰器,请参阅方法三:将装饰器转变为“自我意识”,那么你会找到一个优雅的解决方案)
这是一个可怕的黑客,但你可以使用inspect
模块读取源代码本身并解析它。这在交互式解释器中不起作用,因为检查模块将拒绝以交互模式提供源代码。然而,下面是一个概念证明。
#!/usr/bin/python3
import inspect
def deco(func):
return func
def deco2():
def wrapper(func):
pass
return wrapper
class Test(object):
@deco
def method(self):
pass
@deco2()
def method2(self):
pass
def methodsWithDecorator(cls, decoratorName):
sourcelines = inspect.getsourcelines(cls)[0]
for i,line in enumerate(sourcelines):
line = line.strip()
if line.split('(')[0].strip() == '@'+decoratorName: # leaving a bit out
nextLine = sourcelines[i+1]
name = nextLine.split('def')[1].split('(')[0].strip()
yield(name)
有用!:
>>> print(list( methodsWithDecorator(Test, 'deco') ))
['method']
请注意,必须注意解析和 python 语法,例如@deco
and @deco(...
是有效的结果,但是@deco2
如果我们只是要求,则不应退回'deco'
。我们注意到,根据官方 python 语法http://docs.python.org/reference/compound_stmts.html http://docs.python.org/reference/compound_stmts.html装饰器如下:
decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
我们松了一口气,因为不必处理类似的情况@(deco)
。但请注意,如果您有非常非常复杂的装饰器,这仍然没有真正帮助您,例如@getDecorator(...)
, e.g.
def getDecorator():
return deco
因此,这种解析代码的最佳策略无法检测到这样的情况。不过,如果您使用此方法,那么您真正想要的是定义中该方法之上所写的内容,在本例中是getDecorator
.
根据规范,也有效@foo1.bar2.baz3(...)
作为装饰者。您可以扩展此方法来使用它。您也许还可以扩展此方法以返回<function object ...>
而不是函数的名称,需要付出很多努力。然而,这种方法是黑客且可怕的。
方法三:将装饰器转变为“自我意识”
如果您无法控制装饰者定义(这是对您想要的内容的另一种解释),那么所有这些问题都会消失,因为您可以控制装饰器的应用方式。因此,您可以通过以下方式修改装饰器wrapping它,创造你的own装饰器,并使用that来装饰你的功能。让我再说一遍:你可以创建一个装饰器来装饰你无法控制的装饰器,“启发”它,在我们的例子中,这使它执行之前所做的事情,但是also附加一个.decorator
它返回的可调用对象的元数据属性,允许您跟踪“这个函数是否被装饰?让我们检查 function.decorator!”。和then您可以迭代类的方法,然后检查装饰器是否具有适当的方法.decorator
财产! =) 如此处所示:
def makeRegisteringDecorator(foreignDecorator):
"""
Returns a copy of foreignDecorator, which is identical in every
way(*), except also appends a .decorator property to the callable it
spits out.
"""
def newDecorator(func):
# Call to newDecorator(method)
# Exactly like old decorator, but output keeps track of what decorated it
R = foreignDecorator(func) # apply foreignDecorator, like call to foreignDecorator(method) would have done
R.decorator = newDecorator # keep track of decorator
#R.original = func # might as well keep track of everything!
return R
newDecorator.__name__ = foreignDecorator.__name__
newDecorator.__doc__ = foreignDecorator.__doc__
# (*)We can be somewhat "hygienic", but newDecorator still isn't signature-preserving, i.e. you will not be able to get a runtime list of parameters. For that, you need hackish libraries...but in this case, the only argument is func, so it's not a big issue
return newDecorator
示范为@decorator
:
deco = makeRegisteringDecorator(deco)
class Test2(object):
@deco
def method(self):
pass
@deco2()
def method2(self):
pass
def methodsWithDecorator(cls, decorator):
"""
Returns all methods in CLS with DECORATOR as the
outermost decorator.
DECORATOR must be a "registering decorator"; one
can make any decorator "registering" via the
makeRegisteringDecorator function.
"""
for maybeDecorated in cls.__dict__.values():
if hasattr(maybeDecorated, 'decorator'):
if maybeDecorated.decorator == decorator:
print(maybeDecorated)
yield maybeDecorated
有用!:
>>> print(list( methodsWithDecorator(Test2, deco) ))
[<function method at 0x7d62f8>]
然而,“注册装饰师”必须是最外面的装饰器,否则.decorator
属性注释将会丢失。例如在一列火车上
@decoOutermost
@deco
@decoInnermost
def func(): ...
您只能看到以下元数据decoOutermost
暴露,除非我们保留对“更内部”包装器的引用。
旁注:上面的方法还可以构建一个.decorator
跟踪应用装饰器和输入函数以及装饰器工厂参数的整个堆栈。 =) 例如,如果您考虑注释掉的行R.original = func
,使用这样的方法来跟踪所有包装层是可行的。如果我编写一个装饰器库,这就是我个人会做的,因为它允许深入内省。
之间也有区别@foo
and @bar(...)
。虽然它们都是规范中定义的“装饰器表达式”,但请注意foo
是一个装饰器,而bar(...)
返回一个动态创建的装饰器,然后应用该装饰器。因此你需要一个单独的函数makeRegisteringDecoratorFactory
,这有点像makeRegisteringDecorator
但更多元:
def makeRegisteringDecoratorFactory(foreignDecoratorFactory):
def newDecoratorFactory(*args, **kw):
oldGeneratedDecorator = foreignDecoratorFactory(*args, **kw)
def newGeneratedDecorator(func):
modifiedFunc = oldGeneratedDecorator(func)
modifiedFunc.decorator = newDecoratorFactory # keep track of decorator
return modifiedFunc
return newGeneratedDecorator
newDecoratorFactory.__name__ = foreignDecoratorFactory.__name__
newDecoratorFactory.__doc__ = foreignDecoratorFactory.__doc__
return newDecoratorFactory
示范为@decorator(...)
:
def deco2():
def simpleDeco(func):
return func
return simpleDeco
deco2 = makeRegisteringDecoratorFactory(deco2)
print(deco2.__name__)
# RESULT: 'deco2'
@deco2()
def f():
pass
这个生成器工厂包装器也可以工作:
>>> print(f.decorator)
<function deco2 at 0x6a6408>
bonus我们甚至可以使用方法 #3 尝试以下操作:
def getDecorator(): # let's do some dispatching!
return deco
class Test3(object):
@getDecorator()
def method(self):
pass
@deco2()
def method2(self):
pass
Result:
>>> print(list( methodsWithDecorator(Test3, deco) ))
[<function method at 0x7d62f8>]
正如您所看到的,与 method2 不同,@deco 被正确识别,即使它从未在类中显式编写。与 method2 不同,如果该方法是在运行时添加(手动、通过元类等)或继承的,这也将起作用。
要注意,你也可以装饰一个类,所以如果你“启蒙”一个既用来装饰方法又用来装饰类的装饰器,然后编写一个类在您要分析的类的主体内, then methodsWithDecorator
将返回修饰的类和修饰的方法。人们可以认为这是一项功能,但您可以通过检查装饰器的参数轻松编写逻辑来忽略这些功能,即.original
,实现所需的语义。