如何列出Python模块中的所有函数?

问题描述 投票:347回答:15

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

我想在每一个上调用doc函数。在ruby中,我可以执行类似ClassName.methods的操作,以获取该类上可用的所有方法的列表。 python中有类似的东西吗?

例如。就像是:

from somemodule import foo
print foo.methods # or whatever is the correct method to call
python reflection module inspect
15个回答
118
投票

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


18
投票

对于全局函数,dir()是使用的命令(如大多数答案中所述),但是它将公共函数和非公共函数一起列出。

例如运行:

>>> import re
>>> dir(re)

返回函数/类,如:

'__all__', '_MAXCACHE', '_alphanum_bytes', '_alphanum_str', '_pattern_type', '_pickle', '_subx'

其中一些通常不用于一般编程用途(但是由模块本身,除了像DazAliases的情况,如__doc____file__等)。出于这个原因,将它们与公共列表一起列出可能没有用(这就是Python在使用from module import *时知道要获得什么)。

__all__可用于解决此问题,它返回模块中所有公共函数和类的列表(那些不以下划线开头的函数--_)。请参阅Can someone explain __all__ in Python?以了解__all__的用法。

这是一个例子:

>>> import re
>>> re.__all__
['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'findall', 'finditer', 'compile', 'purge', 'template', 'escape', 'error', 'A', 'I', 'L', 'M', 'S', 'X', 'U', 'ASCII', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', 'VERBOSE', 'UNICODE']
>>>

所有带下划线的函数和类都已删除,只留下那些被定义为公共的函数和类,因此可以通过import *使用。

请注意,并不总是定义__all__。如果不包括在内则会引发AttributeError

这种情况与ast模块有关:

>>> import ast
>>> ast.__all__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ast' has no attribute '__all__'
>>>

3
投票

如果您无法导入所述Python文件而没有导入错误,这些答案都不会起作用。当我检查一个来自具有大量依赖性的大型代码库的文件时,就是这种情况。以下将文件作为文本处理,并搜索以“def”开头的所有方法名称并打印它们及其行号。

import re
pattern = re.compile("def (.*)\(")
for i, line in enumerate(open('Example.py')):
  for match in re.finditer(pattern, line):
    print '%s: %s' % (i+1, match.groups()[0])

2
投票

除了之前答案中提到的dir(模块)或帮助(模块),您还可以尝试: - 打开ipython - import module_name - 键入module_name,按Tab键。它将打开一个小窗口,列出python模块中的所有函数。 它看起来很整洁。

这是列出hashlib模块的所有功能的片段

(C:\Program Files\Anaconda2) C:\Users\lenovo>ipython
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import hashlib

In [2]: hashlib.
             hashlib.algorithms            hashlib.new                   hashlib.sha256
             hashlib.algorithms_available  hashlib.pbkdf2_hmac           hashlib.sha384
             hashlib.algorithms_guaranteed hashlib.sha1                  hashlib.sha512
             hashlib.md5                   hashlib.sha224

1
投票

您可以使用以下方法从shell列出模块中的所有函数:

import module

module.*?

0
投票

这将在列表中附加your_module中定义的所有函数。

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

455
投票

您可以使用dir(module)查看所有可用的方法/属性。还可以查看PyDocs。


145
投票

一旦你imported模块,你可以做:

 help(modulename)

...以交互方式立即获取所有功能的文档。或者您可以使用:

 dir(modulename)

...简单地列出模块中定义的所有函数和变量的名称。


82
投票

检查的一个例子:

from inspect import getmembers, isfunction
from my_project import my_module

functions_list = [o for o in getmembers(my_module) if isfunction(o[1])]

getmembers返回(object_name,object_type)元组的列表。

您可以使用inspect模块中的任何其他isXXX函数替换isfunction。


69
投票
import types
import yourmodule

print([getattr(yourmodule, a) for a in dir(yourmodule)
  if isinstance(getattr(yourmodule, a), types.FunctionType)])

39
投票

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

例如,我让用户为使用zipapp制作的包选择入口点函数。使用importinspect可能会运行误入歧途的代码,导致崩溃,帮助打印出消息,弹出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


24
投票

这样就可以了:

dir(module) 

但是,如果您发现读取返回的列表很烦人,只需使用以下循环来获取每行一个名称。

for i in dir(module): print i

21
投票

对于您不想解析的代码,我建议使用上面基于AST的@csl方法。

对于其他一切,检查模块是正确的:

import inspect

import <module_to_inspect> as module

functions = inspect.getmembers(module, inspect.isfunction)

这给出了[(<name:str>, <value:function>), ...]形式的2元组列表。

上面的简单答案在各种回复和评论中被暗示,但未明确提出。


20
投票

dir(module)是使用脚本或标准解释器的标准方法,如大多数答案中所述。

但是,使用像IPython这样的交互式python shell,您可以使用tab-completion来概览模块中定义的所有对象。这比使用脚本和print查看模块中定义的内容要方便得多。

  • module.<tab>将显示模块中定义的所有对象(函数,类等)
  • module.ClassX.<tab>将向您展示课程的方法和属性
  • module.function_xy?module.ClassX.method_xy?将向您显示该函数/方法的文档字符串
  • module.function_x??module.SomeClass.method_xy??将向您显示函数/方法的源代码。
© www.soinside.com 2019 - 2024. All rights reserved.