How can I avoid circular imports in Python?
<p>I'm having a problem with circular imports.  I have three Python test modules: robot_test.py which is my main script, then two auxiliary modules, controller_test.py and servo_test.py. The idea is that I want controller_test.py to define a class for my microcontroller and servo_test.py to define a class for my servos.  I then want to instantiate these classes in robot_test.py.  Here are my three test modules:</p>

<pre><code>""" robot_test.py """    
from pi.nodes.actuators.servo_test import Servo
from pi.nodes.controllers.controller_test import Controller

myController = Controller()
myServo = Servo()

print myController.ID, myServo.ID


""" controller_test.py """
class Controller():
    def __init__(self, id="controller"):
        self.ID = id


""" servo_test.py """
class Servo():
    def __init__(self, id="servo"):
        self.ID = id
</code></pre>

<p>If I run robot_test.py, I get the expected printout:</p>

<p>controller servo</p>

<p>However, now comes the twist.  In reality, the servo_test.py module depends on controller_test.py by way of robot_test.py.  This is because my servo definitions require an already-instantiated controller object before they themselves can be instantiated.  But I'd like to keep all the initial instantiations in robot_test.py.  So I tried modifying my servo_test.py script as follows:</p>

<pre><code>""" servo_test.py """
from pi.nodes.robots.robot_test import myController
class Servo():
    def __init__(self, id="servo"):
        self.ID = id        
        print myController.ID
</code></pre>

<p>Of course, I could sense that the circularity was going to cause problems and sure enough, when I now try to run robot_test.py I get the error:</p>

<p>ImportError: Cannot import name Servo</p>

<p>which in turn is caused by servo_test.py returning the error:</p>

<p>ImportError: Cannot import name myController</p>

<p>In C# I would define myController and myServo as static objects in robot_test.py and then I could use them in other classes.  Is there anyway to do the same in Python?  One workaround I have found is to pass the myController object to the Servo class as an argument, but I was hoping to avoid having to do this.</p>

<p>Thanks!</p>
