Python circular dependency

I have two files: node.py and path.py , which define two classes: Node and Path respectively.

Until today, the Path definition was referencing a Node object, and so I did

 from node.py import * 

in the path.py file.

However, to date, I have created a new method for Node that references a Path object.

I had problems trying to import path.py : I tried this, and when the program started and called the Path method, which uses Node , the exception grew around Node , which is not defined.

What should I do?

+53
python circular-dependency
May 21 '09 at 20:08
source share
2 answers

Importing Python modules is a great article that explains circular imports in Python.

The easiest way to fix this is to move the path import to the end of the node module.

+93
May 21 '09 at 20:11
source share

Another approach is to import one of the two modules only into functions where it is necessary in the other. Of course, this works best if you only need one or more 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() ... 
+19
Jun 14 '16 at 13:05
source share



All Articles