Python: Import from multiple folders

Some learnings with folder structure and import with Python, I was trying to make a REST Api using Python and Mongo db. My initial folder structure was like this

I had problems with import, I was creating my Flask app in api.py, and I wanted to import my database functions into api.py and I was doing like this “from app.database.db import....” which somehow strangely conflicted the Flask app instance “app = Flask(name)
. Was giving ModuleNotFoundError: No module named ‘app’ Then I made the structure as below, renamed a few folders

Then I had problems in accessing db.py as well as user.py in api.py. Then I found out that I can use relative imports in Python3 using the “.” based import, so in my api.py I did the below and it worked
from .database.db import init_app
from .routes.users import user

I then learned that in Python3, requiring an __init__.py is not that strict. PyCharm IDE helped me in fixing this with smart auto completions. VS Code pylint threw error and I had to put empty __init__.py still. But again it was bit of an experience figuring out these kind of things. Wanted to share this, hope this helps

Leave a Reply

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