Home >Backend Development >Python Tutorial >How Can Circular Imports in Python Be Avoided or Managed?

How Can Circular Imports in Python Be Avoided or Managed?

DDD
DDDOriginal
2024-12-20 02:32:09280browse

How Can Circular Imports in Python Be Avoided or Managed?

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 2: Direct imports at the top of modules
  • Python 3:

    • Direct imports or relative "from" imports at the top of modules
    • Direct imports or non-relative "from" imports with explicitly imported attributes at the bottom of modules

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!

Statement:
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