I’d like to write a method in python which dynamically reads a module and creates a list of all the functions in that module. Then I’d like to loop through this list and call each function. So far I have the following code:
import mymodule
from inspect import getmembers, isfunction
def call_the_functions():
functions_list = [f for f in getmembers(mymodule) if isfunction(f[1])]
for f in functions_list:
result = f()
My problem is that my program is crashing because some of the functions require arguments. I’d like to do something like the following, but don’t know how:
for f in functions_list:
args = [""] * f.expectedNumberOfArguments()
result = f(*args)
Am I going about this the right way? (I’m basically writing a unit test, and the first check is simply that the functions return an object of the right type, regardless of the arguments they are called with.)
Your approach is fundamentally flawed. If written carefully, the functions will reject arguments of invalid type by raising
TypeErroror asserting. Failing that, they will try to access an attribute or method on the parameter and promptly get anAttributeError.It is futile to try to avoid writing unit tests that know something about the functions being tested.