Circular imports arise when two or more modules attempt to import each other. While simple imports may function smoothly, issues emerge when a module attempts to import specific names or attributes from another module that is also trying to import from it.
In direct circular imports, modules attempt to import each other as a whole using direct import statements. For example:
# foo.py import bar # bar.py import foo
Initially, both modules load without issues. However, if one module attempts to access a name that requires the other module to be fully loaded, a runtime error can occur.
To avoid the runtime error, use indirect imports, where modules import attributes or specific names rather than the entire module. For instance:
# foo.py from bar import xyz # bar.py from foo import abc
This approach allows both modules to import the necessary attributes without requiring them to be fully loaded.
Python 2 exhibits slightly different behavior regarding circular imports. In certain specific scenarios, such as importing from the top of a module, not using "from," and only using relative imports, circular imports may work in Python 2 but not in Python 3.
The following examples illustrate additional scenarios where circular imports are permitted in Python:
The above is the detailed content of How Can Circular Imports in Python Be Avoided and What Are Their Consequences?. For more information, please follow other related articles on the PHP Chinese website!