-1

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

MattDMo
  • 100,794
  • 21
  • 241
  • 231
AxelG
  • 37
  • 1
  • 4
  • Does this answer your question? [How to list all functions in a module?](https://stackoverflow.com/questions/139180/how-to-list-all-functions-in-a-module) – Pranav Hosangadi Jul 25 '22 at 14:55
  • @PranavHosangadi almost the same thing but not really the same. There are similarities defiantly, but I would say that the answers here answers more specifically about how to access the function more than just listing it. – AxelG Jul 25 '22 at 15:06

2 Answers2

1

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)
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
  • This worked! However, be aware that this would include other stuff if `foo.py` imports some class or other function they to are included. Just so others knows. But this did solve the problem. Thanks!! – AxelG Jul 25 '22 at 15:02
  • 1
    @AxelG I added a new solution to this hidden danger. – Mechanic Pig Jul 25 '22 at 15:07
-2

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

Crooser
  • 67
  • 3