Search code examples
pythonimporterrorpython-packaging

Why do I receive an ImortError with what seems to be a valid packaging structure?


Any ideas why python is not finding the app module I have defined in this project? I am trying to run plant.py and receiving "Module Not Found". I tried using relative import as well and received "ImportError: attempted relative import with no known parent package".

My project structure is:

├── app
│   ├── __init__.py
│   ├── __pycache__
│   │   └── __init__.cpython-39.pyc
│   ├── api
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   └── __init__.cpython-39.pyc
│   │   └── v1
│   │       ├── __init__.py
│   │       ├── __pycache__
│   │       │   └── __init__.cpython-39.pyc
│   │       ├── console.py
│   │       ├── dependencies.py
│   │       └── endpoints
│   │           ├── __init__.py
│   │           ├── __pycache__
│   │           └── plant.py

and the imports look like:

from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from sqlmodel import select
from app.api.v1.dependencies import get_db
from app.db.connector import init_db
from app.models import Health, Plant, PlantCreate, PlantRead

"""
Traceback (most recent call last):
  File "/Users/ethancloin/Developer/VSCodeProjects/PlantDaddyBackend/app/api/v1/endpoints/plant.py", line 4, in <module>
    from app.api.v1.dependencies import get_db
ModuleNotFoundError: No module named 'app'
"""

I appreciate any insight!


Solution

  • I am trying to run plant.py

    You can't run plant.py directly (e.g. python plant.py) if it's in a package like that, because then the Python import machinery assumes app is in the same directory (and as you found out, you get an import error). Similarly, relative imports won't work because Python doesn't "know" plant.py is in a package; it expects it to be just a script.

    You can use the "run module" (-m) option instead from the directory where app is:

    python -m app.api.v1.endpoints.plant