Skip to content Skip to sidebar Skip to footer

How To Call Every Function In An Imported Python Module

I have a program that I wrote that is creating and maintaining an array and I have another module that I wrote that has functions to manipulate the array. Is it possible to call ev

Solution 1:

I think you want to do something like this:

import inspect

listOfFunctions = [func_name for func_name, funcinmodule.__dict__.iteritems()\
                  if inspect.isfunction(func)]for func_name in listOfFunctions:
    array_func = getattr(array, func_name)
    array_func()

Solution 2:

When you import a module, the __dict__ attribute contains all the things defined in the module (variables, classes, functions, etc.). You can iterate over it and test if the item is a function. This can for example be done by checking for a __call__ attribute:

listOfFunctions = [f for f in my_module.__dict__.values()
                   if hasattr(f,'__call__')]

Then, we can call each function in the list by invoking the __call__ attribute:

for f in listOfFunctions:
    f.__call__()

But be careful! There is no guaranteed order to the dictionary. The functions will be called in a somewhat random order. If order is important, you might want to use a naming scheme that enforces this order (fun01_do_something, fun02_do_something, etc.) and sort the keys of the dictionary first.

Post a Comment for "How To Call Every Function In An Imported Python Module"