2
votes

I'm doing a flask tutorial (http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) and I came upon a behaviour that I couldn't explain. The main directory structure of the tutorial is :

microblog
|
|---- app 
|     |---- __init__.py
|     |---- views.py  
|
|---- flask  
|---- run.py

and the contents of the files are :

microblog/run.py

#!flask/bin/python

from app import app
app.run(debug=True)

microblog/app/init.py

from flask import Flask
app = Flask(__name__)
from app import views 

microblog/app/views.py

from app import app

@app.route("/")
@app.route("/index")

def index():
    return "Hello World!"

everything works but if I transpose these two lines:

app = Flask(__name__)
from app import views

in views.py and then I execute run.py I get:

ImportError: cannot import name app

Why does that happen?

2

2 Answers

1
votes

Because you're trying to import from the newly created variable app. If you want to import variable modules, then use importlib package:

my_module = importlib.import_module(app, 'view')
1
votes

Contrary to what the other answer says, this is a circular import problem. app.__init__ tries to import app.views, which tries to import the app.app Flask created in app.__init__. If the Flask is created before app.__init__ imports app.views, app.views finds app.app. If the Flask is created after the import, it isn't there yet when app.views tries to find it.

Circular imports cause all sorts of horrible problems. It might be difficult, but the best way to handle them is generally to reorganize your code so there aren't circular imports.