如何列出模块中的所有函数?
我的系统上安装了一个 Python 模块,我希望能够查看其中有哪些可用的函数/类/方法。
我想调用每个函数的 help
函数。 在 Ruby 中,我可以执行诸如 ClassName.methods 之类的操作来获取该类上所有可用方法的列表。 Python中有类似的东西吗?
例如:
from somemodule import foo
print(foo.methods) # or whatever is the correct method to call
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(21)
您可以使用 dir(module) 来查看所有可用的方法/属性。 另请查看 PyDocs。
You can use
dir(module)
to see all available methods/attributes. Also check out PyDocs.使用
inspect
模块:另请参阅
pydoc
模块,help() 函数和 pydoc 命令行工具可生成您想要的文档。 您只需向他们提供您希望查看其文档的课程即可。 例如,它们还可以生成 HTML 输出并将其写入磁盘。
Use the
inspect
module:Also see the
pydoc
module, thehelp()
function in the interactive interpreter and thepydoc
command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.一旦您
导入
模块,您就可以执行以下操作:... 以交互方式一次性获取所有函数的文档。 或者您可以使用:
... 简单地列出模块中定义的所有函数和变量的名称。
Once you've
import
ed the module, you can just do:... To get the docs on all the functions at once, interactively. Or you can use:
... To simply list the names of all the functions and variables defined in the module.
使用
inspect.getmembers
获取模块中的所有变量/类/函数等,并传入 < code>inspect.isfunction 作为仅获取函数的谓词:getmembers
返回按字母顺序排序的元组列表(object_name, object)
姓名。您可以将
isfunction
替换为 isXXX 函数rel="noreferrer">检查
模块。Use
inspect.getmembers
to get all the variables/classes/functions etc. in a module, and pass ininspect.isfunction
as the predicate to get just the functions:getmembers
returns a list of tuples(object_name, object)
sorted alphabetically by name.You can replace
isfunction
with any of the otherisXXX
functions in theinspect
module.为了完整起见,我想指出有时您可能想要解析代码而不是导入它。
导入
将执行顶级表达式,这可能是一个问题。例如,我让用户为使用 zipapp。 使用
import
和inspect
可能会运行错误代码,导致崩溃、打印帮助消息、弹出 GUI 对话框等。相反,我使用 ast 模块列出所有顶级函数:
将此代码放入
list.py
中并使用其自身作为输入,我得到:当然,即使对于像 Python 这样相对简单的语言,导航 AST 有时也很棘手,因为 AST 相当低级。 但如果您有一个简单明了的用例,那么它既可行又安全。
不过,缺点是您无法检测运行时生成的函数,例如 foo = lambda x,y: x*y 。
For completeness' sake, I'd like to point out that sometimes you may want to parse code instead of importing it. An
import
will execute top-level expressions, and that could be a problem.For example, I'm letting users select entry point functions for packages being made with zipapp. Using
import
andinspect
risks running astray code, leading to crashes, help messages being printed out, GUI dialogs popping up and so on.Instead I use the ast module to list all the top-level functions:
Putting this code in
list.py
and using itself as input, I get:Of course, navigating an AST can be tricky sometimes, even for a relatively simple language like Python, because the AST is quite low-level. But if you have a simple and clear use case, it's both doable and safe.
Though, a downside is that you can't detect functions that are generated at runtime, like
foo = lambda x,y: x*y
.对于您不想评估的代码,我建议使用基于 AST 的方法(例如 csl 的答案),例如:
对于 其他一切,检查模块是正确的:
这给出了
[(, , ,
) 形式的 2 元组列表。值:函数>), ...]
。上面的简单答案在各种回复和评论中都有暗示,但没有明确指出。
For code that you do not wish to evaluate, I recommend an AST-based approach (like csl's answer), e.g.:
For everything else, the inspect module is correct:
This gives a list of 2-tuples in the form
[(<name:str>, <value:function>), ...]
.The simple answer above is hinted at in various responses and comments, but not called out explicitly.
这可以解决问题:
但是,如果您发现读取返回的列表很烦人,只需使用以下循环来每行获取一个名称即可。
This will do the trick:
However, if you find it annoying to read the returned list, just use the following loop to get one name per line.
正如大多数答案中提到的那样,
dir(module)
是使用脚本或标准解释器时的标准方法。但是,使用像 IPython 这样的交互式 python shell,您可以使用制表符补全来获取模块中定义的所有对象的概述。
这比使用脚本和 print 来查看模块中定义的内容要方便得多。
module.
将显示模块中定义的所有对象(函数、类等)module.ClassX.
将显示方法类module.function_xy?
或module.ClassX.method_xy?
的属性module.function_x??
的文档字符串code> 或module.SomeClass.method_xy??
将向您显示函数/方法的源代码。dir(module)
is the standard way when using a script or the standard interpreter, as mentioned in most answers.However with an interactive python shell like IPython you can use tab-completion to get an overview of all objects defined in the module.
This is much more convenient, than using a script and
print
to see what is defined in the module.module.<tab>
will show you all objects defined in the module (functions, classes and so on)module.ClassX.<tab>
will show you the methods and attributes of a classmodule.function_xy?
ormodule.ClassX.method_xy?
will show you the docstring of that function / methodmodule.function_x??
ormodule.SomeClass.method_xy??
will show you the source code of the function / method.对于全局函数
dir()
是要使用的命令(如大多数答案中所述),但是这同时列出了公共函数和非公共函数。例如运行:
返回如下函数/类:
其中一些通常不用于一般编程用途(但由模块本身使用,除了 DunderAliases 的情况,如
__doc__
、__file__ 等)。 因此,将它们与公共的一起列出可能没有用(这就是 Python 在使用
from module import *
时知道要获取什么的方式)。__all__
可以用来解决这个问题,它返回模块中所有公共函数和类的列表(不以下划线开头的函数和类 -_ )。 看
有人可以解释一下 Python 中的 __all__ 吗? 来了解
__all__< 的使用/代码>。
下面是一个示例:
所有带有下划线的函数和类都已被删除,只留下那些定义为公共的、因此可以通过
import *
使用的函数和类。请注意,
__all__
并不总是已定义。 如果不包含它,则会引发AttributeError
。一个例子是 ast 模块:
For global functions
dir()
is the command to use (as mentioned in most of these answers), however this lists both public functions and non-public functions together.For example running:
Returns functions/classes like:
Some of which are not generally meant for general programming use (but by the module itself, except in the case of DunderAliases like
__doc__
,__file__
ect). For this reason it may not be useful to list them with the public ones (this is how Python knows what to get when usingfrom module import *
).__all__
could be used to solve this problem, it returns a list of all the public functions and classes in a module (those that do not start with underscores -_
). SeeCan someone explain __all__ in Python? for the use of
__all__
.Here is an example:
All the functions and classes with underscores have been removed, leaving only those that are defined as public and can therefore be used via
import *
.Note that
__all__
is not always defined. If it is not included then anAttributeError
is raised.A case of this is with the ast module:
如果您无法在没有导入错误的情况下导入所述 Python 文件,那么这些答案都不起作用。 当我检查来自具有大量依赖项的大型代码库的文件时,就是这种情况。 以下代码将文件作为文本处理,并搜索以“def”开头的所有方法名称并打印它们及其行号。
None of these answers will work if you are unable to import said Python file without import errors. This was the case for me when I was inspecting a file which comes from a large code base with a lot of dependencies. The following will process the file as text and search for all method names that start with "def" and print them and their line numbers.
在当前脚本中查找名称(和可调用对象)
__main__
我试图创建一个独立的 python 脚本,该脚本仅使用标准库来查找当前文件中带有前缀
task_< 的函数/code> 创建
npm run
提供的最小自制版本。TL;DR
如果您正在运行独立脚本,则希望在 sys.modules['__main__']< 中定义的
module
上运行inspect.getmembers
/代码>。 例如,但我想按前缀过滤方法列表并删除前缀以创建查找字典。
示例输出:
较长版本
我想要定义 CLI 任务名称的方法名称,而不必重复自己。
./tasks.py
无参数示例:
使用额外参数运行测试的示例:
您明白了。 随着我的项目越来越多,保持脚本更新比保持自述文件更新更容易,我可以将其抽象为:
Finding the names (and callable objects) in the current script
__main__
I was trying to create a standalone python script that used only the standard library to find functions in the current file with the prefix
task_
to create a minimal homebrewed version of whatnpm run
provides.TL;DR
If you are running a standalone script you want to run
inspect.getmembers
on themodule
which is defined insys.modules['__main__']
. Eg,But I wanted to filter the list of methods by prefix and strip the prefix to create a lookup dictionary.
Example Output:
Longer Version
I wanted the names of the methods to define CLI task names without having to repeat myself.
./tasks.py
Example no arguments:
Example running test with extra arguments:
You get the point. As my projects get more and more involved, it's going to be easier to keep a script up to date than to keep the README up to date and I can abstract it down to just:
您可以使用以下方法从 shell 获取模块中所有函数的列表:
import module
You can use the following method to get list all the functions in your module from shell:
import module
使用
vars(module)
然后使用inspect.isfunction
:vars
超过dir
或 < code>inspect.getmembers 的优点是它按照定义的顺序返回函数,而不是按字母顺序排序。另外,这将包括由
my_module
导入的函数,如果您想过滤掉这些函数以仅获取my_module
中定义的函数,请参阅我的问题获取Python模块中所有定义的函数。Use
vars(module)
then filter out anything that isn't a function usinginspect.isfunction
:The advantage of
vars
overdir
orinspect.getmembers
is that it returns the functions in the order they were defined instead of sorted alphabetically.Also, this will include functions that are imported by
my_module
, if you want to filter those out to get only functions that are defined inmy_module
, see my question Get all defined functions in Python module.除了前面的答案中提到的 dir(module) 或 help(module) 之外,您还可以尝试:
- 打开 ipython
- 导入模块名称
- 输入 module_name,按 Tab 键。 它将打开一个小窗口,列出 python 模块中的所有函数。
看起来非常整洁。
这是列出 hashlib 模块所有函数的片段
Except dir(module) or help(module) mentioned in previous answers, you can also try:
- Open ipython
- import module_name
- type module_name, press tab. It'll open a small window with listing all functions in the python module.
It looks very neat.
Here is snippet listing all functions of hashlib module
输出 :
Output :
Python 文档为此提供了完美的解决方案使用内置函数
dir
。您可以只使用dir(module_name),然后它将返回该模块内的函数列表。
例如,dir(time)将返回
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime ', 'ctime', '日光', 'get_clock_info', 'gmtime', '本地时间', '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']
这是'time'的函数列表模块包含。
The Python documentation provides the perfect solution for this which uses the built-in function
dir
.You can just use dir(module_name) and then it will return a list of the functions within that module.
For example, dir(time) will return
['_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']
which is the list of functions the 'time' module contains.
这会将 your_module 中定义的所有函数附加到列表中。
This will append all the functions that are defined in your_module in a list.
如果您想获取当前文件中定义的所有函数的列表,可以这样做:
作为一个应用程序示例,我使用它来调用单元测试脚本中定义的所有函数。
这是改编自 Thomas Wouters 和 adrian 这里,以及来自 Sebastian Rittau 的另一个问题。
If you want to get the list of all the functions defined in the current file, you can do it that way:
As an application example, I use that for calling all the functions defined in my unit testing scripts.
This is a combination of codes adapted from the answers of Thomas Wouters and adrian here, and from Sebastian Rittau on a different question.
help() 函数效果更好
The help() function works better