Is it possible to list all functions in a module?

user478514 picture user478514 · Oct 28, 2010 · Viewed 51.7k times · Source

I defined a .py file in this format:

foo.py

def foo1(): pass
def foo2(): pass
def foo3(): pass

I import it from another file:

main.py

from foo import * 
# or
import foo

Is it possible list all functions name, e.g. ["foo1", "foo2", "foo3"]?


Thanks for your help, I made a class for what I want, pls comment if you have suggestion

class GetFuncViaStr(object):
    def __init__(self):
        d = {}
        import foo
        for y in [getattr(foo, x) for x in dir(foo)]:
            if callable(y):
               d[y.__name__] = y
    def __getattr__(self, val) :
        if not val in self.d :
           raise NotImplementedError
        else:
           return d[val] 

Answer

aaronasterling picture aaronasterling · Oct 28, 2010

The cleanest way to do these things is to use the inspect module. It has a getmembers function that takes a predicate as the second argument. You can use isfunction as the predicate.

 import inspect

 all_functions = inspect.getmembers(module, inspect.isfunction)

Now, all_functions will be a list of tuples where the first element is the name of the function and the second element is the function itself.