如何解决Python中app.py与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.pywith 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

