0
.
├── mymodule
│   ├── __init__.py
│   └── foo.py
├── tests
    ├── __init__.py
    ├── utils.py
    └── test_module.py

I have the above directory structure for my Python package.

Within the test_module.py file, I need to import tests/utils.py. How should I import it so that I can run the test by using both

  • python tests/test_module.py
  • pytest from the root directory?

Currently, I imported tests/utils.py as follows in the test_module.py file:

from utils import myfunction

Then, pytest will generate the following error:

E   ModuleNotFoundError: No module named 'utils'

If I change to:

from .utils import myfunction

Then, pytest works fine, but python tests/test_module.py generates the following error:

ImportError: attempted relative import with no known parent package

How can I properly import utils.py so that I can use in both ways?

Chang
  • 846
  • 10
  • 23
  • Does this answer your question? [How do I import other Python files?](https://stackoverflow.com/questions/2349991/how-do-i-import-other-python-files) – Nir Alfasi Apr 16 '23 at 20:56

1 Answers1

1
  • When you run test with pytest from root directory, test_module.py is launch as a python module, so relative import is allowed.

  • When you run test with python tests/test_module.py, it is launch as script and relative import is not allowed. But python adds {root directory}/tests directory to sys.path. So you can import with:

    from utils import myfunction
    

You can mix these 2 cases with:

try:
    from .utils import myfunction
except ImportError
    from utils import myfunction

To avoid this try statement, another solution is to run the script with python3 -m tests.test_module from the root directory (PEP 338). In this case test_module.py is loaded as a module and the relative import from .utils import myfunction works fine.

Balaïtous
  • 826
  • 6
  • 9