There is a simple packet structure:

└── myproject | ├── app │  ├── __init__.py │  └── views.py | └── run.py 

__init__.py:

 from flask import Flask app = Flask(__name__) 

run.py:

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

Why in this case the object of the flask class is normally imported from the app package , although it is not a module? When you try to define an app object, for example, in views.py, it is no longer imported.

    2 answers 2

    Why not imported? Everything is perfectly imported :).
    When you declare classes / functions / objects in __init__.py you declare them at the module level. And in the import you write just the name of the module: from module import obj . Similarly, you can make an announcement in a submodule, but then in the import you must specify the name of the submodule: from module.submodule import obj . In your case from app.view import app .

      Import in Python combines two operations :

      1. find (load and initialize) module
      2. 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 .