You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Python中app.py与test.py的循环导入模块错误?

Fixing Circular Import Between app.py and test.py

Hey there, let's work through this circular import issue—it's a super common pitfall when you've got cross-dependencies between modules, and there are a few solid ways to fix it. Here are the most practical solutions:

1. Use Lazy (Function-Level) Imports

Instead of importing test at the top of app.py, move the import inside the app() function itself. This way, the import only happens when the function runs, not when the module first loads, breaking the circular chain.

In app.py:

def app():
    # Import test only when the function is called
    from test import test
    # ... rest of your app logic that uses test()

2. Refactor Shared Logic into a Common Module

If your app.py and test.py are relying on shared code or dependencies, pull that shared stuff into a separate module (like common.py). Then both modules import from this common file instead of each other.

For example:

  • Create common.py with any shared functions/configs
  • In app.py: from common import shared_function
  • In test.py: from common import shared_function

This eliminates the need for cross-module imports entirely, which is the cleanest long-term fix.

3. Import the Entire Module Instead of Specific Objects

Sometimes importing a specific function triggers the circular issue, but importing the whole module doesn't. Try this in app.py:

# Import the entire test module instead of just the test function
import test

def app():
    # Call the function via the module reference
    test.test()

This works because importing the module only creates a reference to it, rather than immediately executing all its top-level code (including the import of app).

4. Restructure Dependencies to Remove the Cross-Import

Take a step back and ask: do you really need app.py to import test? If test.py is importing app to test it, maybe you can adjust the test function to accept the app as a parameter instead of importing it.

In test.py:

def test(app_instance):
    # Test the passed app instance directly
    ...

Then create a separate entry point (like run_tests.py) to tie them together:

from app import app
from test import test

# Create the app instance and pass it to test
test(app())

This way, neither module needs to import the other directly.


内容的提问来源于stack exchange,提问作者sukumar kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:08:15