Circular dependency in Python

circular-dependency, python

Solution

One other approach is importing one of the two modules only in the function where you need it in the other. Sure, this works best if you only need it in one or a small number of 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()
    ...

Problem

I have two files, `node.py` and `path.py`, which define two classes, `Node` and `Path`, respectively. Up to today, the definition for `Path` referenced the `Node` object, and therefore I had done ``` from node.py import * ``` in the `path.py` file. However, as of today I created a new method for `Node` that references the `Path` object. I had problems when trying to import `path.py`: I tried it, and when the program ran and called the `Path` method that uses `Node`, an exception rose about `Node` not being defined. What do I do?

Original source