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
orvars
- 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?