Cannot import name from partially initialized module (most likely due to a circular import)

Https://www.codecademy.com/paths/build-python-web-apps-flask/tracks/flask-sql-databases/modules/flask-sql-alchemy/lessons/flask-read-update-delete-database/exercises/flask-review

When I implement routes.py and import it in app.py, I am getting the above error. It is there in the link and if this is not supported why is it there.

I want to do the following:

  1. create a sepearte routes.py file with db from app.py and add import routes in app.py
  2. create a models.py file and define all models in it. Use it in app.py. I am getting circular reference error as I am using app and db objects in models.py imported from app.py

Hi,

The way I try to prevent this from happening is that I draw a file diagram of my structure and the import dependencies (and where in the code they happen).

It’s a solid way to prevent this from happening on a consistent basis.
Maybe upload your project to github and link it here and some others (and myself) can maybe give a suggestion as to adjustments you can make.

Welcome to the forums :slight_smile:

thanks toasted but I am refering to the code provided in the example and the url is provided above. you can navigate to the code and find it there

Hi,

I don’t have access to pro so I can’t say for sure specifically what you’re dealing with.

But conceptually you can’t circular import. So for example if:

  • in your models you’re importing db from a main file
  • and then you want to import those models into your main file
  • in the main file: the import from the models should come after the db instantiation.

If you import everything at the top it would result in a circular import error of some sort.

Thank you again. It worked. This concept was missing in the course. Now I am able to create model and route files and import them in main file. Working fine now.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.