【问题标题】:In python, how to print the docstrings of all functions defined in an imported module, without the functions that the imported module itself imported?在python中,如何打印导入模块中定义的所有函数的文档字符串,而不包含导入模块本身导入的函数?
【发布时间】:2013-07-30 00:17:57
【问题描述】:

以下代码从导入的模块打印每个函数的文档字符串。但是,结果包括一些未在模块中定义的函数,而是由模块导入的。

import inspect
import my_module

all_functions = inspect.getmembers(my_module, inspect.isfunction)

for i in all_functions:
    print i[0]           # print function name                                                      
    print i[1].__doc__   # print docstring     

我如何只打印模块中定义的函数的文档字符串?

【问题讨论】:

    标签: python function module docstring


    【解决方案1】:

    函数有一个__module__ 属性来存储定义它们的模块的名称。您可以检查它是否与您正在检查的模块匹配。请注意,这经常会错过实际上是模块 API 的一部分但在不同模块中定义的函数。比如heapq.heappush.__module__ == '_heapq',因为这个函数实际上是在一个C模块_heapqimport *ed到Python模块heapq中定义的。

    【讨论】:

    • 太棒了,谢谢!必须将函数转换为 if 语句上的 str 才能进行检查:if str(i[1].__module__) == 'my_module':(参考问题中的示例)
    猜你喜欢
    • 2020-12-06
    • 2015-03-05
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2022-11-11
    • 2013-07-31
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多