0
0
FlaskDebug / FixBeginner · 4 min read

How to Fix Circular Import in Flask: Simple Steps

Circular import errors in Flask happen when two or more files import each other directly or indirectly. To fix this, restructure your code by moving imports inside functions or use an application factory pattern with blueprints to avoid direct circular dependencies.
🔍

Why This Happens

Circular imports occur when two Python files import each other, causing Python to get stuck trying to load both at the same time. In Flask, this often happens when your app object and routes are split across files that import each other.

python
## file: app.py
from flask import Flask
from routes import setup_routes

app = Flask(__name__)
setup_routes(app)

## file: routes.py
from app import app

@app.route('/')
def home():
    return 'Hello, Flask!'
Output
ImportError: cannot import name 'app' from partially initialized module 'app' (most likely due to a circular import)
🔧

The Fix

Move imports inside functions to delay them until needed, or better, use an application factory pattern. This creates the Flask app inside a function and registers routes with blueprints, avoiding circular imports.

python
## file: app.py
from flask import Flask

def create_app():
    app = Flask(__name__)

    from routes import setup_routes
    setup_routes(app)

    return app

## file: routes.py
from flask import Blueprint

bp = Blueprint('main', __name__)

@bp.route('/')
def home():
    return 'Hello, Flask!'

def setup_routes(app):
    app.register_blueprint(bp)
Output
When running the app, visiting '/' shows: Hello, Flask!
🛡️

Prevention

To avoid circular imports in Flask, always use the application factory pattern with blueprints. Keep imports local inside functions if needed. Organize your code so that modules depend on abstractions, not concrete instances. Use linting tools to detect import cycles early.

⚠️

Related Errors

Other common import errors include ModuleNotFoundError when a module path is wrong, or AttributeError when an imported object does not exist. These can often be fixed by checking import paths and names carefully.

Key Takeaways

Circular imports happen when two files import each other directly or indirectly.
Use the application factory pattern and blueprints to avoid circular dependencies in Flask.
Move imports inside functions to delay loading and break import cycles.
Organize code to depend on abstractions, not concrete instances.
Use linting tools to catch circular imports before runtime.