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, and I wanted to import my database functions into 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 as well as in Then I found out that I can use relative imports in Python3 using the “.” based import, so in my 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 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 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 *