ModuleNotFoundError: No module named 'X'

88 Views Asked by At

I got problem with my python project, Let's say I have structure like:

app/
    services/
        service.py
        __init__.py
    repo/
       repository.py
       __init__.py
    tests/
        service-tests/
            test_service.py
        repo-test/
            test_repo.py

I need to import in test_service.py stuff from service.py.

I've been trying like:

from ..services.service import Service

import sys
sys.path.append('..')

from services.service import Service

and some other configuration I found in topics here but all tries resulted in:

ModuleNotFoundError: No module named 'services'

or

ImportError: attempted relative import beyond top-level package

Does anyone know a solution for that? I'm working on macOS and VSCode. Thanks!

1

There are 1 best solutions below

0
Krishnadev N On

Are you trying to run test_service.py directly in a python shell? Then you are running a top-level file with name __main__ and python cannot find a higher level in the package. You might want to read the detail explanation in this answer.

Say you have this (simplified) directory structure:

├── app
│   ├── __init__.py
│   ├── services
│   │   ├── __init__.py
│   │   └── service.py
│   └── tests
│       └── servicetests
│           └── test_service.py
└── testfile.py

Just use

from app.services.service import Service

in the module test_service.py. You can call functions (say, test) from testfile.py as

from app.tests.servicetests.test_service import test