Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unable to import module 'app': No module named 'app'", "errorType": "Runtime.ImportModuleError" [duplicate]

My project structure

mt-kart
     |
      --> src/data_kart
     |        |
     |         -->apis
     |        |
     |         -->__init__.py
     |        |  
     |         -->main.py
      --> tests
             |
              -->__init__.py
             |
              -->conftest.py
             |
              -->test_others.py

  

conftest.py has the following line.

from data_kart.main import fastapi_app

When run pytest from command line from project root(mt-kart). I get the following error

ModuleNotFoundError No module named 'data_kart'

How to make data_kart visible for conftest.py .

like image 301
sjd Avatar asked Feb 04 '26 12:02

sjd


1 Answers

Option 1

Use relative imports:

from ..src.data_kart.main import fastapi_app
fastapi_app()

Please note, the above requires running conftest.py outside the project's directory, like this:

python -m mt-kart.tests.conftest

Option 2

Use the below in conftest.py (ref):

import sys
import os
  
# getting the name of the directory where the this file is present.
current = os.path.dirname(os.path.realpath(__file__))
  
# Getting the parent directory name where the current directory is present.
parent = os.path.dirname(current)

# adding the parent directory to the sys.path.
sys.path.append(parent)
  
# import the module
from src.data_kart.main import fastapi_app

# call the function
fastapi_app()

And if it happens for a module being outside the parent directory of tests, then you can get the parent of the parent direcory and add that one to the sys.path. For example:

parentparent = os.path.dirname(parent)
sys.path.append(parentparent)

Option 3

Same as Option 2, but shorter.

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from src.data_kart.main import fastapi_app
fastapi_app()

Option 4

Options 2 and 3 would work for smaller projects, where only a couple of files need to be updated with the code above. However, for larger projects, you may consider including the directory containing your package directory in PYTHONPATH, as described here (Option 3).

like image 188
Chris Avatar answered Feb 06 '26 00:02

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!