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() ...
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