Search code examples
python-importpython-modulepython-packaging

Python Package with inter-Modul Dependencies


My Folder Structure looks like the following

person-package
|- __init__.py
|- person.py
|- person_manager.py
main.py

person_manager.py imports person.py

import person as x

The main.py imports person_manager.py

import person_package.person_manager as x

When running main.py I get:

ModuleNotFoundError: No module named 'person'

I know, I could solve that by changing the import of person_manager.py to the following

from . import person as x

However, when running now person_manager.py directly, I get:

ImportError: attempted relative import with no known parent package

So I can't test person_manager.py on its own. What is the most elegant way to solve that?


Solution

  • 1. I recommend to always use absolute imports (unless strictly impossible).

    2. person-package is not a valid Python name since it contains a dash -, if I were you I would rename to person_package with an underscore _.

    3. Since person_manager.py is part of a Python importable package (i.e. it is in a directory containing a __init__.py file), then it should not be run as python person_package/person_manager.py, but as python -m person_package.person_manager.