Issues with Mutual or Circular Imports
When two modules in Python attempt to import each other, a seemingly expected outcome would be a successful import. However, scenarios where multiple modules engage in cyclical import attempts present complications.
Direct versus From Imports
If a direct import is attempted (e.g., import foo in bar.py and import bar in foo.py), the import will typically execute successfully. Both modules will be loaded and established with references to each other by the time code execution commences.
The issue arises when "from" imports are employed (e.g., from foo import abc and from bar import xyz). In these cases, each module requires the presence of the other to have already been imported prior to its own import. This creates a deadlock.
Working Circular Imports in Python
Despite the potential for circular import issues, there are instances where they do not cause problems. Examples from specific Python versions include:
Python 3:
Additional Considerations
Star imports (e.g., from foo import *) can introduce further complications that are not covered in the references provided below.
The above is the detailed content of How Can Circular Imports in Python Be Avoided or Managed?. For more information, please follow other related articles on the PHP Chinese website!