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
│   ├── __init__.py
│   ├── main.py
│   ├── dependencies.py
│   └── routers
│   │   ├── __init__.py
│   │   ├── items.py
│   │   └── users.py
│   └── internal
│       ├── __init__.py
│       └── admin.py

				
			

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)])

app.include_router(users.router)
app.include_router(items.router)

@app.get("/")
async def root():
    return {"message": "Hello World"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", 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: https://fastapi.tiangolo.com/tutorial/debugging/?h=debu

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 main.py 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: 402

Leave a Reply

Your email address will not be published.