Circular Dependency in Python with Two Classes
In Python, you may encounter a circular dependency issue when two modules mutually import each other. For instance, consider you have two files, node.py and path.py, defining Node and Path classes, respectively.
Originally, path.py imported Node using from node.py import *. However, after adding a new method in Node that utilizes Path, you encounter an exception while importing path.py, indicating that Node is undefined.
To resolve this circular dependency, consider the following approach:
One option is to import only one of the modules (in this case, path.py) within the specific function/method of the other module (node.py) where it's needed. This approach works well if you require the dependency only in a limited number of functions:
<code class="python"># in node.py from path import Path class Node: ... # in path.py class Path: def method_needs_node(): from node import Node n = Node() ...</code>
By importing node.py only within the method_needs_node() method, you avoid the circular dependency issue.
The above is the detailed content of How to Resolve Circular Dependencies in Python with Two Dependent Classes?. For more information, please follow other related articles on the PHP Chinese website!