获取Python模块中的所有已定义函数 [英] Get all defined functions in Python module
本文介绍了获取Python模块中的所有已定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件 my_module.py
,如下所示:
I have a file my_module.py
that looks like this:
from copy import deepcopy
from my_other_module import foo
def bar(x):
return deepcopy(x)
我想获取在 my_module
中定义的所有功能的列表,而不是导入的列表,在这种情况下,仅是 [bar]
,而不是 deepcopy
或 foo
.
I want to get a list of all the functions defined in my_module
and not the imported ones, in this case just [bar]
, not deepcopy
or foo
.
推荐答案
您可以使用 inspect.isfunction
,然后获取其 .__ module __
属性与模块的 .__ name __
相同的所有函数:
You can use inspect.getmembers
with inspect.isfunction
and then get all the functions whose .__module__
property is the same as the module's .__name__
:
from inspect import getmembers, isfunction
from my_project import my_module
functions = [fn for _, fn in getmembers(my_module, isfunction) if fn.__module__ == my_module.__name__]
这篇关于获取Python模块中的所有已定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文