Home > Backend Development > Python Tutorial > How Can Circular Imports in Python Be Avoided and What Are Their Consequences?

How Can Circular Imports in Python Be Avoided and What Are Their Consequences?

Susan Sarandon
Release: 2024-12-18 05:44:14
Original
806 people have browsed it

How Can Circular Imports in Python Be Avoided and What Are Their Consequences?

Consequences of Circular Imports in Python

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.

Problem: Direct Circular Imports

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
Copy after login

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.

Solution: Indirect Circular Imports

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
Copy after login

This approach allows both modules to import the necessary attributes without requiring them to be fully loaded.

Exception: Python 2 and Specific Scenarios

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.

Additional Examples

The following examples illustrate additional scenarios where circular imports are permitted in Python:

  • Bottom of module, import attribute, not module; "from" import
  • Top of function; "from" import
  • Top of module; "from" import okay; relative okay; Python 3 only

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template