【问题标题】:Is there a way to get the function a decorator has wrapped?有没有办法获得装饰器包装的功能?
【发布时间】:2009-10-09 17:51:55
【问题描述】:

假设我有

@someDecorator
def func():
   '''this function does something'''
   print 1

现在,对象funcsomeDecorator 的一个实例。有什么方法可以访问它所拥有的功能,例如func.getInnerFunction()

例如,如果我需要检索func() 的文档字符串。

【问题讨论】:

    标签: python function nested decorator


    【解决方案1】:

    请参阅 functools.wraps:http://docs.python.org/library/functools.html。装饰器获取原始函数的名称和文档字符串。你可以这样使用它:

    def decorator(f):
        @functools.wraps(f)
        def wrapper():
            ....
    

    【讨论】:

      【解决方案2】:

      SilentGhost 和 sri 对于如何处理这个问题有部分答案。但一般的答案是否定的:没有办法从装饰函数中获取“包装”函数,因为没有要求装饰器首先包装函数。它很可能返回了一个完全不相关的函数,并且对您的原始函数的任何引用都可能已经被垃圾回收了。

      【讨论】:

        【解决方案3】:

        您是否正在寻找类似的东西?

        >>> def dec(f):
            def inner():
                print(f.__doc__)
            return inner
        
        >>> @dec
        def test():
            """abc"""
            print(1)
        
        
        >>> test()
        abc
        

        您将函数显式传递给装饰器,当然您可以访问它。

        【讨论】:

          【解决方案4】:

          您可以将包装函数附加到内部函数

          In [1]: def wrapper(f):
             ...:     def inner():
             ...:         print "inner"
             ...:     inner._orig = f
             ...:     return inner
             ...: 
          
          In [2]: @wrapper
             ...: def foo():
             ...:     print "foo"
             ...:     
             ...:     
          
          In [3]: foo()
          inner
          
          In [4]: foo._orig()
          foo
          

          【讨论】:

            【解决方案5】:

            您可以尝试使用undecorated library:

            使用您的示例func,您可以简单地执行以下操作来返回原始函数:

            undecorated(func)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-05-11
              • 2012-02-29
              • 2019-06-16
              • 2020-12-10
              • 2019-08-20
              • 2021-12-05
              相关资源
              最近更新 更多