方法一:基本注册装饰器
我已经在这里回答了这个问题:Calling functions by array index in Python =)
方法二:源码解析
如果您无法控制 类 定义,这是您想要假设的一种解释,这是不可能 (没有代码阅读反射),因为例如装饰器可以是一个无操作装饰器(就像在我的链接示例中一样),它只返回未修改的函数。 (尽管如此,如果您允许自己包装/重新定义装饰器,请参阅方法 3:将装饰器转换为“自我意识”,然后您会找到一个优雅的解决方案)
这是一个可怕的骇客,但您可以使用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 和 @deco(... 是有效结果,但如果我们只请求 'deco',则不应返回 @deco2。我们注意到,根据http://docs.python.org/reference/compound_stmts.html 的官方python 语法,装饰器如下:
decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
不必处理像@(deco) 这样的案件,我们松了一口气。但是请注意,如果您有非常复杂的装饰器,例如@getDecorator(...),这仍然对您没有帮助,例如
def getDecorator():
return deco
因此,这种最好的代码解析策略无法检测到这样的情况。虽然如果你使用这个方法,你真正想要的是写在定义中方法之上的内容,在这种情况下是getDecorator。
根据规范,将@foo1.bar2.baz3(...) 作为装饰器也是有效的。您可以扩展此方法以使用它。您可能还可以扩展此方法以返回 <function object ...> 而不是函数的名称,但需要付出很多努力。然而,这种方法是骇人听闻和可怕的。
方法3:将装饰器转换为“自我意识”
如果您无法控制 decorator 定义(这是您想要的另一种解释),那么所有这些问题都会消失,因为您可以控制关于如何应用装饰器。因此,您可以通过 包装 来修改装饰器,创建自己的 装饰器,并使用 that 来装饰您的功能。让我再说一遍:你可以制作一个装饰器来装饰你无法控制的装饰器,“启发”它,在我们的例子中,它可以做它之前做的事情,但是也附加一个.decorator 元数据属性到它返回的可调用对象,允许您跟踪“此函数是否已装饰?让我们检查 function.decorator!”。 然后您可以遍历类的方法,并检查装饰器是否具有适当的.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 和 @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>
奖励让我们甚至用方法 #3 尝试以下操作:
def getDecorator(): # let's do some dispatching!
return deco
class Test3(object):
@getDecorator()
def method(self):
pass
@deco2()
def method2(self):
pass
结果:
>>> print(list( methodsWithDecorator(Test3, deco) ))
[<function method at 0x7d62f8>]
如您所见,与方法 2 不同,@deco 被正确识别,即使它从未明确写入类中。与 method2 不同,如果该方法是在运行时添加(手动、通过元类等)或继承的,这也将起作用。
请注意,你也可以装饰一个类,所以如果你“启发”一个既用于装饰方法又用于装饰类的装饰器,然后在你要分析的类的主体内编写一个类 /em>,然后methodsWithDecorator 将返回修饰类以及修饰方法。可以将其视为一项功能,但您可以通过检查装饰器的参数(即.original)轻松编写逻辑来忽略这些功能,以实现所需的语义。