Find functions explicitly defined in a module (python)

ぃ、小莉子 提交于 2019-11-28 21:16:43

Are you looking for something like this?

import sys, inspect

def is_mod_function(mod, func):
    return inspect.isfunction(func) and inspect.getmodule(func) == mod

def list_functions(mod):
    return [func.__name__ for func in mod.__dict__.itervalues() 
            if is_mod_function(mod, func)]


print 'functions in current module:\n', list_functions(sys.modules[__name__])
print 'functions in inspect module:\n', list_functions(inspect)

EDIT: Changed variable names from 'meth' to 'func' to avoid confusion (we're dealing with functions, not methods, here).

How about the following:

grep ^def my_module.py

You can check __module__ attribute of the function in question. I say "function" because a method belongs to a class usually ;-).

BTW, a class actually also has __module__ attribute.

Stefano Borini

Every class in python has a __module__ attribute. You can use its value to perform filtering. Take a look at example 6.14 in dive into python

the python inspect module is probably what you're looking for here.

import inspect
if inspect.ismethod(methodInQuestion):
    pass # It's a method
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!