Linked Questions

Popular Questions

Module does not recognize itself to be part of package

Asked by At

I've created a Python3 project with cookiecutter with the following structure (simplified for readability):

── docs
│   ├── ...
....
├── my_application
│   ├── __init__.py
│   ├── my_application.py
│   └── util
|       └── utility.py
├── README.rst
├── requirements_dev.txt
├── setup.cfg
├── setup.py
├── tests
│   ├── test_my_application.py
│   └── test_utility.py
└── ...

my_application.py

#!/usr/bin/env python3

from my_application.util import utility

utility.hello_utility()

def hello_app():
    return "Main App"

test_my_application.py

#!/usr/bin/env python3
import pytest

from my_application import my_application

def test_main_app():
    assert my_application.hello_app() == 'Main App'

With these import statements, my tests run fine but running the application gives the following error:

from my_application.util import utility
ModuleNotFoundError: No module named 'my_application.util';
'my_application' is not a package

Changing that import in my_application.py to from util import utility reverses the situation: The program runs but the tests can't import the main module with from my_application import my_application anymore.

Weirdly enough, the following still works:

test_utility.py

from my_application.util import utility
def test_utility():
    assert utility.hello_utility() == 'Found'

I know, I can probably solve this by applying one of the usual hacks, e.g., appending to the sys.path or modifying the PYTHONPATH variable, but I hope to understand why the main module is not recognizing itself being part of the package when other modules do. I'm aware of the fact that it also depends on how and from where you run your modules. In my case, I only want to run the main module my_application.py directly and obviously the tests.

Related Questions