Home > Software design >  Loop over all function in a file in python
Loop over all function in a file in python

Time:07-26

So let's say I have a file like:

#foo.py

def bar_one(a):
  return a   1 

def bar_two(a):
  return a   2 

...

def bar_n(a):
  return a   n 

but I want to test this by check that the return type of all the functions are of type int.

So what I would like to do is somthing like this:

# test_foo.py

import foo 

def test_foo():
  for func in foo:
    assert isinstance(func(1), int)

is there a way of doing

CodePudding user response:

Module has a attribute __dict__, which is a dictionary containing all objects in the module, so you can get all callable objects by using filter and callable (If you require that the object must be a function object, you can use inspect.isfunction):

import foo

for func in filter(callable, foo.__dict__.values()):   # Or use vars(foo) to obtain __dict__ implicitly
    assert isinstance(func(1), int)

To filter functions from other modules, you can judge the module name of the object:

for val in foo.__dict__.values():
    if callable(val) and val.__module__ == foo.__name__:
        assert isinstance(val(1), int)

CodePudding user response:

You can use the dir function to have a list of all attributes and methods of a module and then call them with foo[function_name]()

Or use the getmembers function and filter the resulting list for functions with isfunction that gives a list of functions that you can call directly

  • Related