如何获取带特定装饰器的Python类的所有方法?
如何获取一个指定类A中所有使用了@decorator2
这个装饰器的方法?
class A():
def method_a(self):
pass
@decorator1
def method_b(self, b):
pass
@decorator2
def method_c(self, t=5):
pass
7 个回答
如果你可以控制装饰器的话,可以使用装饰器类,而不是用函数来做:
class awesome(object):
def __init__(self, method):
self._method = method
def __call__(self, obj, *args, **kwargs):
return self._method(obj, *args, **kwargs)
@classmethod
def methods(cls, subject):
def g():
for name in dir(subject):
method = getattr(subject, name)
if isinstance(method, awesome):
yield name, method
return {name: method for name,method in g()}
class Robot(object):
@awesome
def think(self):
return 0
@awesome
def walk(self):
return 0
def irritate(self, other):
return 0
如果我调用 awesome.methods(Robot)
,它会返回
{'think': <mymodule.awesome object at 0x000000000782EAC8>, 'walk': <mymodulel.awesome object at 0x000000000782EB00>}
为了进一步解释@ninjagecko在方法二:源代码解析中给出的精彩回答,你可以使用Python 2.6引入的ast
模块来进行自我检查,只要inspect模块能够访问源代码。
def findDecorators(target):
import ast, inspect
res = {}
def visit_FunctionDef(node):
res[node.name] = [ast.dump(e) for e in node.decorator_list]
V = ast.NodeVisitor()
V.visit_FunctionDef = visit_FunctionDef
V.visit(compile(inspect.getsource(target), '?', 'exec', ast.PyCF_ONLY_AST))
return res
我添加了一个稍微复杂一点的装饰器方法:
@x.y.decorator2
def method_d(self, t=5): pass
结果:
> findDecorators(A)
{'method_a': [],
'method_b': ["Name(id='decorator1', ctx=Load())"],
'method_c': ["Name(id='decorator2', ctx=Load())"],
'method_d': ["Attribute(value=Attribute(value=Name(id='x', ctx=Load()), attr='y', ctx=Load()), attr='decorator2', ctx=Load())"]}
方法一:基本注册装饰器
我已经在这里回答了这个问题:通过数组索引调用Python中的函数 =)
方法二:源代码解析
如果你无法控制类的定义,这可以理解为你想要的情况,那么这是不可能的(没有代码读取反射),因为例如装饰器可能是一个无操作装饰器(就像我链接的例子)仅仅返回未修改的函数。(不过,如果你允许自己包装/重新定义装饰器,看看方法三:将装饰器转换为“自我意识”,那么你会找到一个优雅的解决方案)
这是一种非常糟糕的黑客方式,但你可以使用inspect
模块来读取源代码并解析它。这在交互式解释器中是行不通的,因为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
不应该被返回。我们注意到,根据官方Python语法,装饰器如下所示:
decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
我们松了一口气,不用处理像@(deco)
这样的情况。但请注意,如果你有非常复杂的装饰器,比如@getDecorator(...)
,这仍然不会真正帮助你,例如:
def getDecorator():
return deco
因此,这种解析代码的最佳策略无法检测到这样的情况。不过,如果你使用这种方法,你真正想要的是在定义中写在方法上方的内容,在这种情况下就是getDecorator
。
根据规范,@foo1.bar2.baz3(...)
作为装饰器也是有效的。你可以扩展这个方法来处理这种情况。你也可能能够扩展这个方法,以返回<function object ...>
而不是函数的名称,但这需要很多努力。不过,这种方法确实是黑客式的,效果不佳。
方法三:将装饰器转换为“自我意识”
如果你无法控制装饰器的定义(这也是你想要的另一种理解),那么所有这些问题都不复存在,因为你可以控制装饰器的应用方式。因此,你可以通过包装它来修改装饰器,创建你自己的装饰器,并用它来装饰你的函数。让我再说一遍:你可以制作一个装饰器,装饰你无法控制的装饰器,给它“启蒙”,在我们的例子中,这使它在之前的基础上还附加一个.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>]
如你所见,与方法二不同,@deco被正确识别,尽管它从未在类中显式写出。与方法二不同,如果方法在运行时(手动、通过类的元类等)添加或继承,这也将有效。
请注意,你也可以装饰一个类,因此如果你“启蒙”一个用于装饰方法和类的装饰器,然后在你想分析的类的主体内编写一个类,那么methodsWithDecorator
将返回装饰的类和装饰的方法。有人可能会认为这是一个特性,但你可以轻松编写逻辑,通过检查装饰器的参数,即.original
,来忽略这些,以实现所需的语义。