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

时间:2008-09-26 12:38:52

标签: python reflection module inspect

我的系统上安装了python模块,我希望能够看到它中可用的函数/类/方法。

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

例如。类似的东西:

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

21 个答案:

答案 0 :(得分:434)

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

答案 1 :(得分:139)

一旦你import编辑了模块,你就可以这样做:

 help(modulename)

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

 dir(modulename)

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

答案 2 :(得分:113)

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

答案 3 :(得分:75)

检查的一个例子:

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。

答案 4 :(得分:67)

import types
import yourmodule

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

答案 5 :(得分:36)

为了完整性'为了清楚起见,我想指出有时你可能想要解析代码而不是导入代码。 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

答案 6 :(得分:23)

这样可以解决问题:

dir(module) 

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

for i in dir(module): print i

答案 7 :(得分: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??会显示函数/方法的源代码。

答案 8 :(得分:20)

对于您不想解析的代码,我推荐上面基于AST的@csl方法。

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

import inspect

import <module_to_inspect> as module

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

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

上面的简单答案在各种回复和评论中都有所暗示,但没有明确说明。

答案 9 :(得分:15)

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

例如跑步:

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

返回函数/类,如:

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

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

__all__可用于解决此问题,它返回模块中所有公共函数和类的列表(那些以下划线开头 - {{1} })。看到 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__

这种情况与ast模块有关:

AttributeError

答案 10 :(得分: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])

答案 11 :(得分:2)

在当前脚本中查找名称(和可调用对象)__main__

我试图创建一个独立的 Python 脚本,该脚本仅使用标准库在当前文件中查找带有前缀 task_ 的函数,以创建 npm run 提供的最小自制版本。

TL;DR

如果您正在运行独立脚本,您希望在 inspect.getmembers 中定义的 module 上运行 sys.modules['__main__']。例如,

inspect.getmembers(sys.modules['__main__'], inspect.isfunction)

但我想按前缀过滤方法列表并去除前缀以创建查找字典。

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

示例输出:

{
 'install': <function task_install at 0x105695940>,
 'dev': <function task_dev at 0x105695b80>,
 'test': <function task_test at 0x105695af0>
}

更长的版本

我想要方法的名称来定义 CLI 任务名称,而不必重复。

./tasks.py

#!/usr/bin/env python3
import sys
from subprocess import run

def _inspect_tasks():
    import inspect
    return { f[0].replace('task_', ''): f[1] 
        for f in inspect.getmembers(sys.modules['__main__'], inspect.isfunction)
        if f[0].startswith('task_')
    }

def _cmd(command, args):
    return run(command.split(" ") + args)

def task_install(args):
    return _cmd("python3 -m pip install -r requirements.txt -r requirements-dev.txt --upgrade", args)

def task_test(args):
    return _cmd("python3 -m pytest", args)

def task_dev(args):
    return _cmd("uvicorn api.v1:app", args)

if __name__ == "__main__":
    tasks = _inspect_tasks()

    if len(sys.argv) >= 2 and sys.argv[1] in tasks.keys():
        tasks[sys.argv[1]](sys.argv[2:])
    else:
        print(f"Must provide a task from the following: {list(tasks.keys())}")

无参数示例:

λ ./tasks.py
Must provide a task from the following: ['install', 'dev', 'test']

使用额外参数运行测试的示例:

λ ./tasks.py test -qq
s.ssss.sF..Fs.sssFsss..ssssFssFs....s.s    

你明白了。随着我的项目越来越多,保持脚本更新比保持 README 更新更容易,我可以将其抽象为:

./tasks.py install
./tasks.py dev
./tasks.py test
./tasks.py publish
./tasks.py logs

答案 12 :(得分:2)

Python documentation使用内置函数dir为此提供了完美的解决方案。

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

例如, dir(time)将返回

['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'time_ns', 'timezone', 'tzname', 'tzset']

这是“时间”模块包含的功能列表。

答案 13 :(得分:2)

除了先前答案中提到的目录(模块)或帮助(模块),您还可以尝试:
  - 打开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

答案 14 :(得分:1)

import sys
from inspect import getmembers, isfunction
fcn_list = [o[0] for o in getmembers(sys.modules[__name__], isfunction)]

答案 15 :(得分:1)

r = globals()
sep = '\n'+100*'*'+'\n' # To make it clean to read.
for k in list(r.keys()):
    try:
        if str(type(r[k])).count('function'):
            print(sep+k + ' : \n' + str(r[k].__doc__))
    except Exception as e:
        print(e)

输出:

******************************************************************************************
GetNumberOfWordsInTextFile : 

    Calcule et retourne le nombre de mots d'un fichier texte
    :param path_: le chemin du fichier à analyser
    :return: le nombre de mots du fichier

******************************************************************************************

    write_in : 

        Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode a,
        :param path_: le path du fichier texte
        :param data_: la liste des données à écrire ou un bloc texte directement
        :return: None


 ******************************************************************************************
    write_in_as_w : 

            Ecrit les donnees (2nd arg) dans un fichier txt (path en 1st arg) en mode w,
            :param path_: le path du fichier texte
            :param data_: la liste des données à écrire ou un bloc texte directement
            :return: None

答案 16 :(得分:1)

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

import module

module.*?

答案 17 :(得分:1)

如果你想获得当前文件中定义的所有函数的列表,你可以这样做:

# Get this script's name.
import os
script_name = os.path.basename(__file__).rstrip(".py")

# Import it from its path so that you can use it as a Python object.
import importlib.util
spec = importlib.util.spec_from_file_location(script_name, __file__)
x = importlib.util.module_from_spec(spec)
spec.loader.exec_module(x)

# List the functions defined in it.
from inspect import getmembers, isfunction
list_of_functions = getmembers(x, isfunction)

作为一个应用程序示例,我使用它来调用在我的单元测试脚本中定义的所有函数。

这是改编自 Thomas Woutersadrian 此处以及 Sebastian Rittau 对不同问题的答案的代码组合。

答案 18 :(得分: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))

答案 19 :(得分:0)

使用vars(module),然后使用inspect.isfunction过滤掉不是功能的所有内容:

import inspect
import my_module

my_module_functions = [f for _, f in vars(my_module).values() if inspect.isfunction(f)]

varsdir相比,inspect.getmembers的优势在于,它按定义的顺序返回函数,而不是按字母顺序排序。

此外,这将包括my_module导入的函数,如果要过滤掉这些函数以仅获取my_module中定义的函数,请参阅我的问题Get all defined functions in Python module。 / p>

答案 20 :(得分:-5)

使用dir(模块)不是(或至少不再适用)。代码应如下所示:

dir('module') or dir('modules') 

或者您指定所需的模块:dir('sys')以从模块名称sys生成结果。 dir()会在您需要dir('')时返回错误。 * help('')将返回大多数功能可用的帮助信息。例如; help('modules')将返回模块帮助信息。

感谢所有的选票。当我发布这个时,我正在使用Python3.2.2和其他3x版本。关键是要使用('stuff')而不是之前的(东西)。但是我假设你的所有人都坚持使用Python2或使用更新版本的PC而不是像我一样的手机。

http://effbot.org/librarybook/sys.htm