Skip to content Skip to sidebar Skip to footer

Transitive Import Error: Modulenotfounderror: No Module Named '...'

I'm confused now. Here is the project tree: project - source - - lib - - - __init__.py - - - utils.py - - - stats.py - test - - lib - - - test_stats.py stats.py has import utils,

Solution 1:

import utils in Python 3 is absolute import, Python looks module utils in sys.path.

When you run stats.py as a script Python adds the directory project/source/lib/ to sys.path. So import utils in the script works.

But when you run test_stats.py Python doesn't add project/source/lib/ to sys.path. So import utils doesn't work.

A way to overcome that is to use relative import: from . import utils. In stats.py it means: do not search sys.path, import module utils from the same directory as stats.py. But then you loose ability to run stats.py as a script. So move main code from stats.py to a separate script outside of lib/.

A slightly different solution is to move main code from stats.py to module __main__.py and execute the module using python -m lib (project/source/ must be in sys.path).

Post a Comment for "Transitive Import Error: Modulenotfounderror: No Module Named '...'"