How to Fix Circular Import in Flask: Simple Steps
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.
## 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!'
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.
## 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)
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.