flask icon indicating copy to clipboard operation
flask copied to clipboard

Why `from . import views` can solve circle import in Flask?

Open zjyExcelsior opened this issue 10 years ago • 2 comments

I learn from Larger Applications.In this document, It says: "all the view functions (the ones with a route() decorator on top) have to be imported in the init.py file. Not the object itself, but the module it is in."
I don't know why when I do this: from . import views,It succeed.Though from views import * can also work well.
I organize these file like this:

myapplication/
  runner.py
  myflask/
    __init__.py
    views.py
    templates/
    static/
    ...

runner.py:

from testFlask import app
app.run()

myflask/init.py:

from flask import Flask
app = Flask(__name__)
from . import views # why this can work????

myflask/views.py:

from . import app
@app.route('/')
def index():
    return 'Hello World!'

and I run it:

$ cd myapplication
$ python runner.py

It's OK to run this Flask app. However I want to know why from . import views can solve this circle import problem in flask? And why the doc says: Not the object itself, but the module it is in????

zjyExcelsior avatar May 09 '16 09:05 zjyExcelsior

Please use IRC or Stack Overflow for this - the issue tracker is not the right place for general questions.

ThiefMaster avatar May 09 '16 09:05 ThiefMaster

to explain - modules that are still in evaluation are already importable

so declaring the app object fist means it can be imported from other places and the cycle is resolved

RonnyPfannschmidt avatar May 09 '16 09:05 RonnyPfannschmidt