0

I'm currently setting up a test suite for a file called main.py. The test file is called test_main.py. Here's an example:

# main.py
def add(a,b):
    return a+b
#test_main.py
import pytest
from main import *

def test_add():
    assert add(1,2) == 3

For reasons which are outside the scope of this question, I would like to dynamically load the function add in test_main.py as opposed to calling it directly. I'm already aware this is possible using the following

  • globals or vars
  • use of importlib
  • use of eval

However, I'd like to see if there's another option. globals and vars are bad practice. eval is allright, but it doesn't return the function object and I have to do some string manipulation to get the function call, including its arguments right. importlib is by far the best option, but main.py happens to contain functions which I want to import the "normal" way. It feels wrong to import functions in test_main.py using both an import statement and the importlib module.

So, is there a better way? One which is more pythonic?

user32882
  • 5,094
  • 5
  • 43
  • 82
  • 1
    My initial reaction is that dynamically loading functions feels unpythonic to begin with. – Code-Apprentice Oct 20 '21 at 17:26
  • Please see https://stackoverflow.com/questions/2386714/why-is-import-bad as a starting point for why 'from main import *' is poor practice – Joshua Voskamp Oct 20 '21 at 17:27
  • I've seen many established open source codebases that make extensive use of things like `getattr` which are in essence dynamically extracting bits and pieces of already instantiated classes – user32882 Oct 20 '21 at 17:27
  • @JoshuaVoskamp Ok that I understand and agree with. However, since I'm not actually making a package for the moment (just refactoring some legacy VBA code), I think its OK to get away with `from x import *`, since the code will probably change enormously along the way anyway. – user32882 Oct 20 '21 at 17:30
  • Perhaps you might find https://realpython.com/python-import/#using-importlib useful? – Joshua Voskamp Oct 20 '21 at 17:31

0 Answers0