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
│   ├──
│   ├──
│   └── util
|       └──
├── README.rst
├── requirements_dev.txt
├── setup.cfg
├── tests
│   ├──
│   └──
└── ...

#!/usr/bin/env python3

from my_application.util import utility


def hello_app():
    return "Main App"

#!/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 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:

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 directly and obviously the tests.

Related Questions