How to Fix Relative Import - ImportError in PyCharm, Python 3

Today, I will talk about how to fix the ImportError in PyCharm. Regularly this error is pretty much easy to fix. However, there is a scenario that makes this error is not easy to fix.

This issue happens when I was working the FastAPI. My project structure is for multiple files.

├── app
│   ├──
│   ├──
│   ├──
│   └── routers
│   │   ├──
│   │   ├──
│   │   └──
│   └── internal
│       ├──
│       └──


And here is part of my code:

					import uvicorn
from fastapi import Depends, FastAPI

from .dependencies import get_query_token, get_token_header
from .internal import admin
from .routers import items, users

app = FastAPI(dependencies=[Depends(get_query_token)])


async def root():
    return {"message": "Hello World"}

if __name__ == "__main__":, host="", port=8000)

When the code like this and run the command: uvicorn app.main:app –reload, it works perfect. However, when using PyCharm to debug, the terminal output the ImportError.

ImportError: attempted relative import with no known parent package

FastAPI Debugging with PyCharm:

You can delete the dot and then debug the project by PyCharm. It will works. However, this approach is pretty annoying. When deploying it, you need modify all relative package to absolute path.

Here has a perfect solution for it. You only need to change the main file package to absolute path and keep relative path in sub files.

					import uvicorn
from fastapi import Depends, FastAPI

from app.dependencies import get_query_token, get_token_header
from app.internal import admin
from app.routers import items, users

app = FastAPI(dependencies=[Depends(get_query_token)])

The file is in the app directory. Therefore, the app.dependencies will resolve the path issue and it also works when running uvicorn app.main:app –reload

Hopefully, this article can resolve your problem.

If you like, you can read more books regarding Python:

Hits: 1543

Leave a Reply

Your email address will not be published. Required fields are marked *