Ben
Ben

Reputation: 21615

Python ImportError: attempted relative import with no known parent package

I'm learning fastapi. I have a very simple project structure like this

.
├── __init__.py
├── database.py
├── main.py
├── models.py
├── requirements.txt
└── schemas.py

Inside main.py is

from fastapi import FastAPI
from typing import Optional
from . import schemas, models
from .database import engine

app = FastAPI()

# more code here...

but when I run this with uvicorn main:app --reload I get the error

...
from . import schemas, models
ImportError: attempted relative import with no known parent package

I don't understand why I'm getting this error. I'm loosely following this tutorial. I've also read through numerous related SO questions (1 2 3), but none seem to match my situation.

Upvotes: 1

Views: 1489

Answers (2)

Jack
Jack

Reputation: 41

Although your logic of "." directory is right, relative imports always relay on environment configurations, which may vary depending by IDE, venv and such stuffs, E.G. the env may vary at runtime in VScode based on the launch.json and settings.json

I'd suggest you to better structure your project so that it contains package folders containing the __init__.py and the homonym module name, thus you can setup the import behave in the __init__.py file.

Exempli Gratia: Here Database, Model1 and Model2 are classes in the database/database.py and models/models.py

Where database/__init__.py is defined as follows to link the Database class inside database.py the import at the "upper" folder

And the models/__init__py similarly links models.py classes to the "upper" folder

Notice how referring to directories with the from keyword uses the __init__.py inside the called directory by default to import objects to main, thus you could define specific instances or variables along with constants directly into the __init__.py at will along with any kind of operation (although is not always a good thing to do...)

Upvotes: 0

Sairam
Sairam

Reputation: 33

Instead of importing the files as "from . import schemas, models", Try importing it directly like this - import schemas,models.I think this might work.

Upvotes: 1

Related Questions