How does python import order affect names?
Question: 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?


Answer: 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')
    

