Find functions explicitly defined in a module (python)

后端 未结 5 2001
北恋
北恋 2020-12-03 04:48

Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume m

5条回答
  •  -上瘾入骨i
    2020-12-03 05:41

    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).

提交回复
热议问题