简体   繁体   English

从框架对象获取文档字符串

[英]Get the docstring from a frame object

I use the following code to 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()

but I also want to get the docstring from the caller's method in the called method. 但我也想从被调用方法的调用者方法中获取文档字符串。 How do I do that? 我怎么做?

You can't, because you do not have a reference to the function object. 您不能,因为您没有对函数对象的引用。 It's the function object that has the __doc__ attribute, not the associated code object. 具有__doc__属性的功能对象,而不是关联的代码对象。

You'd have to use the filename and linenumber information to try and make an educated guess as to what the docstring might be, but due to the dynamic nature of Python that is not going to be guaranteed to be correct and current. 您必须使用文件名和行号信息来尝试对文档字符串可能是什么进行有根据的猜测,但是由于Python的动态特性,不能保证它是正确的和最新的。

I wouldn't necessarily advise it, but you can always use the globals() to find the function by name. 我不一定会建议这样做,但是您始终可以使用globals()来按名称查找该函数。 It would go something like this: 它会像这样:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM