r/learnpython • u/zaphodikus • 11h ago
dynamic import module path hack in pytest
In order to validate (using pytest) a python module which is not in my path or relative folders, I want to hack the import path.
I'm wondering what alternatives there are to doing a PYTHONPATH hack.
I could use https://docs.pytest.org/en/7.1.x/reference/reference.html#confval-pythonpath, but that applies to the entire session as I understand it. And I only want to change one suite, so I am writing a quick fixture that will roughly look like (hard-coded for simplicity)
@pytest.fixture(scope="function")
def modules_path():
old_path = sys.path
extra_path= os.path.abspath("c:/otherpath/other") # replace constant with a func
sys.path.insert(0, extra_path)
yield extra_path
sys.path = old_path
I've always felt there was a better way to do import path hacks that nobody had ever told me about. Or is this @fixture approach not as evil as I assumed it was, and was merely biased by painful memories whenever I did use it. Alternatives?