phndiaye phndiaye -4 years ago 77
Python Question

ImportError when importing from a lower module

I'm trying to import an object named

db
(SQLAlchemy object) in in a module of my Flask Project in order to use the SQLAlchemy in my models (
models.py
). Assuming my package is named
Foo
and contains the
db
object in his
__init__.py
fileĀ , when i try to do a
from Foo import db
, i get the following error:

ImportError: cannot import name db


I'm using Flask Blueprint to dispatch my project into two applications (dashboard and frontend) and each of them contains an
__init__.py
file. Only the
models.py
is throwing this error, i got some imports in my views file (as importing the login manager) and everything goes well.

Any idea of what it could be ?

UPDATE : The traceback

Traceback (most recent call last):
File "run.py", line 4, in <module>
from kuchiyose import app
File "/path_to_project/kuchiyose/kuchiyose/__init__.py", line 60, in <module>
from kuchiyose import dashboard, frontend
File "/path_to_project/kuchiyose/kuchiyose/dashboard/__init__.py", line 10, in <module>
from dashboard import views
File "/path_to_project/kuchiyose/kuchiyose/dashboard/__init__.py", line 10, in <module>
from dashboard import views
File "/path_to_project/kuchiyose/kuchiyose/dashboard/views.py", line 8, in <module>
from kuchiyose.dashboard.models import User
File "/path_to_project/kuchiyose/kuchiyose/dashboard/models.py", line 3, in <module>
from kuchiyose import db

ImportError: cannot import name db

Answer Source

there appears to be circular imports:

  • kuchiyose/__init__.py imports from kuchiyose.dashboard.views
  • kuchiyose/dashboard/views.py imports from kuchiyose.dashboard.models
  • kuchiyose/dashboard/models.py imports from kuchiyose

see e.g. Circular (or cyclic) imports in Python for more info...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download