Import in Python combines two operations :
- find (load and initialize) module
- enter new names in the current environment (as assignment operation
= )
Why and how does the app from app import app work?
from module import name imports the module module and if it does not contain the name name, then an attempt is made to import the module.name module. If name already exists, then the name module is not imported, but simply the analog name = module.name is executed.
In the code presented in the question, the app name already exists in the app module, so the app module is simply imported and a new name is created in the current namespace (analog: app = __import__('app').app ).
Why, in this case, the flask class's app object is normally imported from the app package, although it is not a module?
All names assigned in app/__init__.py are available as app.имя after importing the app package ( import app ).
app.app already available, so there is no attempt to import the app.app module. If you delete the app = ... from __init__.py , then an attempt will be made to import the app.app module.
It is recommended that app = Flask(__name__) be placed inside the create_app(...) function so that different parameters can be passed (for example, for tests).
When you try to define an app object, for example, in views.py, it is no longer imported.
Nested modules are not implicitly imported ( from app import app ) does not import the views.py module. If views.py contains name = 'value' , then to import the name name into run.py should write:
from app.views import name
If there is a desire to go deep, then all the details of the import system are described in the Python specification .