stef
stef

Reputation: 27749

Python, unable to import

I've asked a similar question before and without having found a solution I've simplified my code as much as possible to illustrate the problem.

The code below runs fine, until I include from run import db in models.py. Then I get ImportError: cannot import name 'Site' (full error below)

However when I use from models import * then everything runs fine again (but I don't want to do that).

Why does this happen?

run.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///database/db.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy()

from models import Site
# from models import *
print (Site.hello())

models.py

# Uncommenting the import line below produces the error
# from run import db

class Site():

    def hello():
        print ("hello world")

Error

    (venv) abc:projectx me$ python run.py
Traceback (most recent call last):
  File "run.py", line 16, in <module>
    from models import Site
  File "/Users/me/projectx/models.py", line 1, in <module>
    from run import db
  File "/Users/me/projectx/run.py", line 16, in <module>
    from models import Site
ImportError: cannot import name 'Site'

Directory structure

projectx
    __pycache__
    database
    venv
    __init__.py
    run.py
    models.py

Upvotes: 3

Views: 183

Answers (1)

Isma
Isma

Reputation: 15190

You are importing Site from module "models" into module "run" and db from module "run" into module "models" so you have a circular dependency problem.

You should keep your models simple so I would remove the dependency from module "run" inside "models" but if you still need it, then you should consider creating a single module that includes both because in this case, it would be sensible to make a single unit containing all dependant code.

Upvotes: 3

Related Questions