Get all defined functions in Python module

情到浓时终转凉″ 提交于 2021-02-04 08:24:52

问题


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)

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.


回答1:


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__]


来源:https://stackoverflow.com/questions/65251833/get-all-defined-functions-in-python-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!