如何使用给定的装饰器获取 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

原文由 kraiz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 864
2 个回答

方法一:基础注册装饰器

我已经在这里回答了这个问题: Calling functions by array index in Python =)


方法二:源码解析

如果您无法控制 class definition ,这是对您想要假设的一种解释,这是 不可能 的(没有代码阅读反射),因为例如装饰器可能是无操作装饰器(如在我的链接示例中)仅返回未修改的函数。 (尽管如此,如果您允许自己包装/重新定义装饰器,请参阅 方法 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']

请注意,必须注意解析和 python 语法,例如 @deco@deco(... 是有效结果,但是 @deco2 --- 是有效的结果,但是 —对于 'deco' 。我们注意到,根据 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 它返回的可调用对象的元数据属性,允许您跟踪“这个函数是否被装饰?让我们检查一下 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>]

正如您所看到的,与 method2 不同,@deco 被正确识别,即使它从未明确写入类中。与 method2 不同,如果方法是在运行时添加(手动、通过元类等)或继承的,这也将起作用。

请注意,您还可以装饰一个类,因此如果您“启发”一个用于装饰方法和类的装饰器,然后 在您要分析的类的主体中 编写一个类,那么 methodsWithDecorator 将返回装饰类和装饰方法。人们可以认为这是一项功能,但您可以通过检查装饰器的参数(即 .original )轻松编写逻辑来忽略这些功能,以实现所需的语义。

原文由 ninjagecko 发布,翻译遵循 CC BY-SA 3.0 许可协议

扩展@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())"]}

原文由 Shane Holloway 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题