"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Resolve Circular Dependency Issues in Python?

How to Resolve Circular Dependency Issues in Python?

Published on 2024-11-08
Browse:850

How to Resolve Circular Dependency Issues in Python?

Circular Dependency Resolution in Python

In Python, it is possible to encounter circular dependencies when modules rely on each other for their definition. One such scenario is present when two files, node.py and path.py, define classes Node and Path, respectively, with each referencing the other.

Initially, path.py imported node.py to access the Node object. However, a recent modification introduced a method in Node that references the Path object. This created a circular dependency, leading to an exception while importing path.py.

There are several approaches to resolve circular dependencies:

1. Forward Reference:

Use a forward reference in one module to declare the class name of the other module without実際にimporting it. In this case, path.py would declare the Node class with a forward reference:

from typing import ForwardRef

Node = ForwardRef("Node")

class Path:
    def method_needs_node(self, node: Node):
        ...

2. Lazy Import:

Import the required module only when it is needed within a function. This is particularly suitable when the dependency is required in only one or a few functions:

# in node.py 
from path import Path
class Node 
    ...

# in path.py
class Path:
  def method_needs_node(): 
    from node import Node
    n = Node()
    ...
Release Statement This article is reprinted at: 1729326978 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3