1

I want to capture the name of ALL non-built-in functions from a specific module and put them into a list.

Let's say I wrote func_1() and func_2() inside the module test.py. Then, from inside another module, I want to do something like:

import test
my_list_of_functions = all_funcs_from(test)

Dir() returns built-in functions together, and I wasn't able to do the tricky with help()

42piratas
  • 555
  • 1
  • 9
  • 26

2 Answers2

2

This should return all top-level functions from the imported module.

from types import FunctionType

def all_funcs_from(module):
    return filter(lambda f: isinstance(f, FunctionType), module.__dict__.values())

Builtin functions are of type types.BuiltinFunctionType. But note that something like f = functools.partial(g, 5) would not be captured by this method.

You can also use hasattr(f, '__call__') to widen your search for callables in general.

All this depends on your actual requirements.

The answers to this question are very helpful in this regard.

Community
  • 1
  • 1
Michael Hoff
  • 6,119
  • 1
  • 14
  • 38
1

You can get all the function names in your module with inspect.getmembers

Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.

import types, inspect

# my_module is your module
r = inspect.getmembers(my_module, lambda o: isinstance(o, types.FunctionType))
function_names = [i[0] for i in r] # list of only function names

You can simplify the predicate by using inspect.isfunction(credits to @user2357112):

r = inspect.getmembers(my_module, inspect.isfuction)
function_names = [i[0] for i in r]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • 1
    You can supply `inspect.isfunction` for the predicate. – user2357112 Jun 30 '16 at 21:38
  • @user2357112 Thanks. Right away! – Moses Koledoye Jun 30 '16 at 21:39
  • @moses-koledoye Almost that. But it is returning the name of only one of the functions from the module, and returns it several times like this: `[('description', ), ('description', ), ('description', ), ('description', ), ('description', )]` – 42piratas Jun 30 '16 at 21:43
  • @MosesKoledoye It worked with `inspect.isfunction`. Thank you very much, Moses! – 42piratas Jun 30 '16 at 21:48
  • @anquadros Please note that top-level functions returned by ``functools.partial`` are not functions in the sense of ``inspect.isfunction`` and ``isinstance(f, types.FunctionType)``. – Michael Hoff Jun 30 '16 at 22:01