Why is there no circular reference in the case of Python?

Flask project, the project structure is as follows:

clipboard.png

app/__init__.py use from app.home import home as home_blueprint to introduce home ;

< hr > The code in

home/__init__.py is as follows:

from flask import Blueprint

home = Blueprint("home", __name__)

import app.home.views

and the code in app/home/views.py is as follows:

from . import home  

@home.route("/")
def index():
    return "Home Page"
from at the beginning of

. Is import home from home/__init__.py import ? While home/__init__.py ends with import app.home.views to import content from views.py , won"t there be circular references?

Mar.03,2021

1. This is the flask project. We can make it clear that all module operations are carried out under the current operation directory, that is, sys.__path__ is not involved when importing the module.
2. All modules are imported to load memory, so before loading memory, we Python will add all the imported modules to the sys.modules dictionary and add the name of the module to the Local namespace of the module that is calling import.
3. Let's review the package / module imports in the flask project.
3.1Use from app.home import home as home_blueprint in app/__init__.py to introduce home . The action here is to save the package name and path of home to the sys.modules dictionary, and introduce the package name home into the Local namespace of the app module.
3.2, home/__init__.py ends with import app.home.views to import content from views.py . The package name and path of views are also saved to sys.modules , and the package name views is introduced into the Local namespace of the home module.

< H2 > Tip: A module will not be imported repeatedly. < / H2 >

so far, everything seems to be fine.

4, however, the point is that views also needs to import blueprints home , which is obviously the problem of circular import . Remember, the loop import problem is a real problem that leads to ModuleNotFoundError: No module named errors. But the loop importing can be cracked, that is, the at the end of the home/__init__.py text is written on the text.
5. What if it is written in front of ? In home/__init__.py , home = Blueprint ('home', _ _ name__) is defined as home this package. Before you define it, when it comes to calling home itself, you will definitely report an error. So, the problem written before or after is based on the code home = Blueprint ('home', _ _ name__) created by the blueprint.

Menu