【问题标题】:How do I get the docstring from a calling module?如何从调用模块获取文档字符串?
【发布时间】:2021-12-20 11:44:23
【问题描述】:

我可以得到主脚本的__doc__ 字符串吗?

这是从命令行运行的启动脚本:python a.py

模块 a.py

import b
b.func()

模块 b.py

def func():
    ???.__doc__

如何将调用模块作为对象获取?

我不是在询问如何将文件名作为字符串获取。我知道如何从堆栈跟踪中检索文件名。我不想通过手动解析来检索 doc 字符串。另外,由于循环导入循环,我认为我不能只通过m = __import__(a) 导入。

【问题讨论】:

  • for a.py 把导入时不想运行的代码全部放在if __name__=="__main__".里面,然后从b导入a。然后使用文档字符串。

标签: python docstring


【解决方案1】:

a.py

"""
Foo bar
"""

import b
if __name__ == '__main__':
    b.show_your_docs()

b.py

def show_your_docs():
    name = caller_name(1)
    print(__import__(name).__doc__)

其中 caller_name 是来自 gist 的代码

这种方法的缺点是它获取模块名称的字符串表示并重新导入它,而不是获取对模块(类型)的引用。

【讨论】:

    【解决方案2】:

    这是来自@MatthewMartin 接受的答案的完整解决方案:

    def show_your_docs():
        name = caller_name(1)
        print(__import__(name).__doc__)
    
    def caller_docstring(level=1):
        name = caller_name(level)
        return __import__(name).__doc__
    
        def caller_name(skip=2):
            def stack_(frame):
                framelist = []
                while frame:
                    framelist.append(frame)
                    frame = frame.f_back
                return framelist
    
            stack = stack_(sys._getframe(1))
            start = 0 + skip
            if len(stack) < start + 1:
                return ''
            parentframe = stack[start]
    
            name = []
            module = inspect.getmodule(parentframe)
            if module:
                name.append(module.__name__)
            if 'self' in parentframe.f_locals:
                name.append(parentframe.f_locals['self'].__class__.__name__)
            codename = parentframe.f_code.co_name
            if codename != '<module>':  # top level usually
                name.append(codename)  # function or a method
            del parentframe
            return ".".join(name)
    
    text = caller_docstring(2)
    

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 2016-10-18
      • 1970-01-01
      • 2023-02-24
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多