我使用以下代码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()
但我也希望从被调用方法中的调用者方法中获取docstring。我该怎么做?
答案 0 :(得分:1)
您不能,因为您没有对 function 对象的引用。它是具有__doc__
属性的函数对象,而不是关联的代码对象。
你必须使用filename和linenumber信息来尝试对docstring可能是什么做出有根据的猜测,但由于Python的动态特性不能保证是正确和最新的。
答案 1 :(得分:0)
我不一定会建议它,但你总是可以使用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()