简体   繁体   中英

Get all defined functions in Python module

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM