【问题标题】:Get the docstring from a frame object从框架对象中获取文档字符串
【发布时间】:2013-03-11 14:40:29
【问题描述】:

我用下面的代码get the caller's method name in the called method

import inspect

def B():
    outerframe = inspect.currentframe().f_back
    functionname = outerframe.f_code.co_name
    docstring = ??
    return "caller's name: {0}, docsting: {1}".format(functionname, docstring)

def A():
    """docstring for A"""
    return B()


print A()

但我也想在被调用方法中从调用者的方法中获取文档字符串。我该怎么做?

【问题讨论】:

    标签: python introspection inspect


    【解决方案1】:

    你不能,因为你没有对 function 对象的引用。它是具有__doc__ 属性的函数对象,而不是关联的代码对象。

    您必须使用文件名和行号信息来尝试对文档字符串可能是什么做出有根据的猜测,但由于 Python 的动态特性,不能保证它是正确和最新的。

    【讨论】:

      【解决方案2】:

      我不一定建议这样做,但您始终可以使用 globals() 按名称查找函数。它会是这样的:

      import inspect
      
      def B():
          """test"""
          outerframe = inspect.currentframe().f_back
          functionname = outerframe.f_code.co_name
          docstring = globals()[ functionname ].__doc__
          return "caller's name: {0}, docsting: {1}".format(functionname, docstring)
      
      def A():
          """docstring for A"""
          return B()
      
      print A()
      

      【讨论】:

      • 函数名不一定是存储它的名称;您可以像任何其他对象一样重新分配功能。它们也不总是全局的,类上的方法当然不是全局的。
      • 是的,就像我说的那样,当然不会推荐它,但如果你绝对需要在一个小程序中快速修复,那么它是可能的
      猜你喜欢
      • 2010-10-17
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多