Is it possible to list all functions in a module?

Question:

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] 
Asked By: user478514

||

Answers:

you can use dir to explore a namespace.

import foo
print dir(foo)

Example: loading your foo in shell

>>> import foo
>>> dir(foo)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'foo1', 'foo2', 'foo3']
>>> 
>>> getattr(foo, 'foo1')
<function foo1 at 0x100430410>
>>> k = getattr(foo, 'foo1')
>>> k.__name__
'foo1'
>>> callable(k)
True
>>> 

You can use getattr to get the associated attribute in foo and find out if it callable.

Check the documentation : http://docs.python.org/tutorial/modules.html#the-dir-function

and if you do – “from foo import *” then the names are included in the namespace where you call this.

>>> from foo import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'atexit', 'foo1', 'foo2', 'foo3']
>>> 

The following brief on introspection in python might help you :

Answered By: pyfunc

For a wild import

from foo import * 
print dir()

you can use dir() without a parameter to show objects in the current module’s namespace. This will most probably include more than just the content of foo.

In case of an absolute import (which you should prefer by the way) you can pass the module to dir():

import foo
print dir(foo)

Also check the documentation of dir. As you only wanted functions, you might want to think about using inspect.isfunction. Hope you don’t use that list for non-debugging purposes.

Answered By: AndiDog

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.

Answered By: aaronasterling

Try using inspect module like below for exmaple if module –> temp.py

In [26]: import inspect

In [27]: import temp

In [28]: l1 = [x.__name__ for x in temp.__dict__.values() if inspect.isfunction(x)]

In [29]: print l1
['foo', 'coo']
Answered By: shahjapan

Like
aaronasterling said, you can use the getmembers functions from the inspect module to do this.

import inspect

name_func_tuples = inspect.getmembers(module, inspect.isfunction)
functions = dict(name_func_tuples)

However, this will include functions that have been defined elsewhere, but imported into that module’s namespace.

If you want to get only the functions that have been defined in that module, use this snippet:

name_func_tuples = inspect.getmembers(module, inspect.isfunction)
name_func_tuples = [t for t in name_func_tuples if inspect.getmodule(t[1]) == module]
functions = dict(name_func_tuples)
Answered By: Flimm

if wanting to list functions of the current module (i.e., not an imported one), you could also do something like this:

import sys
def func1(): pass
def func2(): pass

if __name__ == '__main__':
    print dir(sys.modules[__name__])
Answered By: verboze
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.