Loop over all function in a file in python

Question:

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

Asked By: AxelG

||

Answers:

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

Answered By: Crooser

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)
Answered By: Mechanic Pig
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.