liveBook · Manning

Circular reference

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A circular reference problem is a dependency structure in which modules directly or indirectly require each other in a cycle that prevents valid importing or initialization.

A circular reference occurs when modules depend on one another in a cycle. In a Flask application, app.py may import feature modules while those modules need the Flask app instance, creating an import structure Python will not allow. section 7.3.1

The practical fix is architectural rather than a patch to one import: move most application code into a Python package and create the app through a factory function. section 7.3.1

Resolve the dependency cycle by:

  • Creating a package with an __init__.py file to organize application modules and namespaces. section 7.3.1
  • Defining create_app() to instantiate the Flask app and contain application setup. section 7.3.1

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Explains the dependency structure and gives a package-and-factory remedy, without descending into Python import internals.
Examples
Uses a MyBlog app.py layout, a package directory tree, create_app(), and Flask command-line launch examples.
What it assumes
Assumes familiarity with Python modules and Flask app instances while refreshing package creation through __init__.py.
What you can do after
Diagnose/debug with it by recognizing import cycles and restructuring Flask code around a package and factory.
How it connects
Connects Python modules, packages, namespaces, Flask app instances, and application factories.

Also explained in

Compare how 3 books explain circular reference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.