# 导入错误：无法从部分初始化的模块'myapp'导入名称'app'（很可能是由于循环导入）

- **ID:** `python/flask-import-error-circular`
- **领域:** python
- **类别:** module_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

Flask应用模块之间的循环导入，常见于views.py从app.py导入，同时app.py也在模块级别从views.py导入。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Use lazy imports inside functions or request handlers** (90% 成功率)
   ```
   def create_app():
    from myapp.views import some_view
    app.register_blueprint(some_view)
    return app
   ```
2. **Refactor to use Flask application factory pattern** (85% 成功率)
   ```
   # app.py
def create_app():
    app = Flask(__name__)
    with app.app_context():
        from . import views
        app.register_blueprint(views.bp)
    return app
   ```

## 无效尝试

- **Moving all imports to the top of each file without restructuring** — Doesn't break the cycle; Python still tries to initialize both modules simultaneously. (95% 失败率)
- **Using 'from myapp import app' inside a function without lazy loading** — If the function is called during module initialization, the cycle persists. (70% 失败率)
