我的系统上安装了一个Python模块,我希望能够看到其中有哪些函数/类/方法可用。

我想对每一个都调用帮助函数。在Ruby中,我可以做一些类似ClassName的事情。方法获取该类上所有可用方法的列表。Python中有类似的东西吗?

例如:

from somemodule import foo
print(foo.methods)  # or whatever is the correct method to call

当前回答

这将把your_module中定义的所有函数添加到列表中。

result=[]
for i in dir(your_module):
    if type(getattr(your_module, i)).__name__ == "function":
        result.append(getattr(your_module, i))

其他回答

Python文档提供了使用内置函数dir的完美解决方案。

您可以只使用dir(module_name),然后它将返回该模块中的函数列表。

例如,dir(time)将返回

[' _STRUCT_TM_ITEMS’,‘__doc__’,‘__loader__’,‘__name__’,‘__package__’,‘__spec__’,‘altzone’,‘asctime’,‘ctime’,‘阳光’,‘get_clock_info’,‘gmtime’,‘作用’,‘mktime’,‘单调’,‘monotonic_ns’,‘perf_counter’,‘perf_counter_ns’,‘process_time’,‘process_time_ns’,‘睡眠’,‘strftime’,‘strptime’,‘struct_time’,‘时间’,‘time_ns’,“时区”,“tzname”,“tzset”)

它是'time'模块包含的函数列表。

import types
import yourmodule

print([getattr(yourmodule, a) for a in dir(yourmodule)
  if isinstance(getattr(yourmodule, a), types.FunctionType)])
import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]

使用inspect模块:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

还可以查看pydoc模块、交互式解释器中的help()函数和生成所需文档的pydoc命令行工具。您可以只给他们您希望看到的类的文档。例如,它们还可以生成HTML输出并将其写入磁盘。

为了完整起见,我想指出,有时您可能希望解析代码而不是导入代码。导入将执行顶级表达式,这可能是一个问题。

例如,我让用户为用zipapp生成的包选择入口点函数。使用导入和检查的风险包括运行错误的代码、导致崩溃、打印帮助消息、弹出GUI对话框等等。

相反,我使用ast模块列出所有顶级函数:

import ast
import sys

def top_level_functions(body):
    return (f for f in body if isinstance(f, ast.FunctionDef))

def parse_ast(filename):
    with open(filename, "rt") as file:
        return ast.parse(file.read(), filename=filename)

if __name__ == "__main__":
    for filename in sys.argv[1:]:
        print(filename)
        tree = parse_ast(filename)
        for func in top_level_functions(tree.body):
            print("  %s" % func.name)

把这段代码放在list.py中,并使用它自己作为输入,我得到:

$ python list.py list.py
list.py
  top_level_functions
  parse_ast

当然,有时导航AST可能很棘手,即使对于Python这样相对简单的语言也是如此,因为AST是相当低级的。但是如果你有一个简单而清晰的用例,它是可行的和安全的。

不过,缺点是您无法检测在运行时生成的函数,如foo = lambda x,y: x*y。