如何使用给定的decorator获取python类的所有方法
如何获得用@decorator2修饰的给定类a的所有方法如何使用给定的decorator获取python类的所有方法,python,class,methods,decorator,inspect,Python,Class,Methods,Decorator,Inspect,如何获得用@decorator2修饰的给定类a的所有方法 class A(): def method_a(self): pass @decorator1 def method_b(self, b): pass @decorator2 def method_c(self, t=5): pass 方法1:基本注册修饰符 我已经在这里回答了这个问题:=) 方法2:源代码解析 如果您无法控制类的定义(这是您想要假设的一种
class A():
def method_a(self):
pass
@decorator1
def method_b(self, b):
pass
@decorator2
def method_c(self, t=5):
pass
方法1:基本注册修饰符
我已经在这里回答了这个问题:=)
方法2:源代码解析 如果您无法控制类的定义(这是您想要假设的一种解释),那么这是不可能的(没有代码读取反射),因为例如,decorator可能是一个只返回未修改函数的无操作decorator(如我的链接示例中所示)。(尽管如此,如果您允许自己包装/重新定义装饰器,请参见方法3:将装饰器转换为“自我意识”,那么您将找到一个优雅的解决方案) 这是一个可怕的黑客攻击,但是您可以使用
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']
>>> print(list( methodsWithDecorator(Test2, deco) ))
[<function method at 0x7d62f8>]
请注意,必须注意解析和python语法,例如@deco
和@deco(…
是有效的结果,但是如果我们只要求@deco'
,则不应返回@deco2
。我们注意到,根据装饰程序的官方python语法,如下所示:
decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
对于不必处理像@(deco)
这样的情况,我们松了一口气。但是请注意,如果您有非常复杂的装饰器,例如@getDecorator(…)
,这仍然不能真正帮助您
def getDecorator():
return deco
因此,这种解析代码的最佳策略无法检测到这样的情况。虽然如果使用此方法,您真正想要的是定义中方法顶部的内容,在本例中是getDecorator
根据规范,将@foo1.bar2.baz3(…)
作为装饰器也是有效的。您可以扩展此方法来处理此问题。您还可以扩展此方法以返回
,而不是函数名,这需要付出大量努力。然而,此方法非常粗糙和可怕
方法3:将装饰者转换为“自我意识” 如果您无法控制装饰器的定义(这是您想要的另一种解释),然后所有这些问题都消失了,因为您可以控制如何应用装饰器。因此,您可以通过包装装饰器来修改装饰器,创建您自己的装饰器,并使用它来装饰您的函数。让我再说一次:您可以使装饰器装饰您无法控制的装饰器,“启发”它,在我们的例子中,它使它做它以前做过的事情,但也将
.decorator
元数据属性附加到它返回的可调用项中,允许您跟踪“此函数是否已修饰?让我们检查function.decorator!”.和然后您可以迭代类的方法,只需检查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(Test, 'deco') ))
['method']
>>> print(list( methodsWithDecorator(Test2, deco) ))
[<function method at 0x7d62f8>]
您只能看到最外层的
公开的元数据,除非我们保留对“更内部”包装的引用
旁注:上述方法还可以构建一个.decorator
,它跟踪应用的decorator和输入函数以及decorator工厂参数的整个堆栈例如,如果您考虑注释行>代码> r.Orth.Func ,那么使用这样的方法来跟踪所有包装层是可行的。如果我写了一个decorator库,我个人会这么做,因为它允许深入反省
@foo
和@bar(…)
之间也有区别。虽然它们都是规范中定义的“decorator表达式”,但请注意,foo
是一个decorator,而bar(…)
返回一个动态创建的decorator,然后应用它。因此,您需要一个单独的函数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(…)
:
该发电机工厂包装器也可以工作:
>>> print(f.decorator)
<function deco2 at 0x6a6408>
结果:
>>> print(list( methodsWithDecorator(Test3, deco) ))
[<function method at 0x7d62f8>]
打印(列表(methodsWithDecorator(Test3,deco)))
[]
正如您所见,与method2不同,@deco被正确识别,即使它从未在类中显式编写。与method2不同的是,如果在运行时(手动、通过元类等)添加或继承该方法,则该方法也会起作用
请注意,您也可以修饰类,因此如果您“启发”一个用于修饰方法和类的修饰器,然后在要分析的类的主体中编写一个类,那么
methodsWithDecorator
将返回修饰类和修饰方法。人们可以认为这是一个特性,但是您可以很容易地编写逻辑来忽略那些通过检查装饰器的参数,即<代码>原始的< /代码>,以实现所需的语义。 也许,如果装饰器不是太复杂的(但是我不知道是否有一个更少的杂乱无章的方式)。
为了扩展@ninjagecko在方法2:源代码解析中的出色答案,您可以使用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())"]}
解决此问题的一个简单方法是将代码放入decorator,该decorator将传入的每个函数/方法添加到数据集(例如列表) e、 g 现在,每个带有装饰器的函数都将被添加到函数中
@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())"]}
def deco(foo):
functions.append(foo)
return foo
def methodsWithDecorator(cls, decoratorName):
sourcelines = inspect.getsourcelines(cls)[0]
return [ sourcelines[i+1].split('def')[1].split('(')[0].strip()
for i, line in enumerate(sourcelines)
if line.split('(')[0].strip() == '@'+decoratorName]
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
{'think': <mymodule.awesome object at 0x000000000782EAC8>, 'walk': <mymodulel.awesome object at 0x000000000782EB00>}