Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get around circular import error when using Sphinx

I have a module robot.py with a similarly named class. I also have a cop.py module and a robber.py module, each with similarly named classes as well, each subclassing from Robot. I broke them up to keep the files shorter.

In creating a Robot object, the Robot has multiple Cop and Robber attributes (i.e., each Robot has some other cops and robbers that it keeps track of).

I've gotten around circular import issues with the following (simplified) code structure in Robot.py, where I put module import statements at the very bottom:

class Robot(object):
    def __init__(self):
        self.other_cop = cop_module.Cop()
        self.other_robber = robber_module.Robber()

import cops_and_robots.robo_tools.cop as cop_module
import cops_and_robots.robo_tools.robber as robber_module

(Of course, each Cop.py and Robber.py both have from cops_and_robots.robo_tools.robot import Robot at the beginning of their files)

This works fine in practice. However, when I try to autodoc using Sphinx, I get the following issue:

/Users/nick/Dropbox/Syncs/Code/Github/cops_and_robots/src/cops_and_robots/docs/cops_and_robots.robo_tools.rst:41: WARNING: autodoc: failed to import module u'cops_and_robots.robo_tools.robber'; the following exception was raised:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 335, in import_object
__import__(self.modname)
File "/Users/nick/Dropbox/Syncs/Code/Github/cops_and_robots/src/cops_and_robots/robo_tools/robber.py", line 22, in <module>
from cops_and_robots.robo_tools.robot import Robot
File "/Users/nick/Dropbox/Syncs/Code/Github/cops_and_robots/src/cops_and_robots/robo_tools/robot.py", line 520, in <module>
import cops_and_robots.robo_tools.robber as robber_module
AttributeError: 'module' object has no attribute 'robber'

Is there a good way for me to restructure my code, or to modify Sphinx, so that I don't fall into this circular dependency issue?

like image 389
Nick Sweet Avatar asked Jul 04 '26 12:07

Nick Sweet


1 Answers

If you have some funky circular dependency in your python code (hey we've all been there) you may need to force Sphinx to import your dependencies in a particular order. I can't help you with which order you need to use, but you can add import statements into conf.py:

import os
import sys
sys.path.insert(0, os.path.abspath(YOUR_MODULE_PATH)
import YOUR_MODULE_DEPENDENCY_TO_RESOLVE_FIRST
like image 147
cracked_machine Avatar answered Jul 07 '26 03:07

cracked_machine