Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Circular imports


I'm writing two classes which depend on each other. They are very similar to Integer and Rational, so let's just take that example. Rationals are constructed using instances of Integer. But some operations on an Integer return a Rational (such as division).

Currently I have two files: and At the top of I do

from integer import Integer, Integers

And within a few specific methods of Integer (e.g. _div_()), I do

from rational import Rational


from rational import Rationals

This worked fine, but now that I am running the doctests using the SageMath doctesting framework:

./sage -t

I get errors. I traced these errors back to the following problem. My parents Integers and Rationals are unique: they inherit from UniqueRepresentation. When running the tests, two different instances of Integers are created. I think this is because I first create such an instance, then I perform for example a division, which imports from, which in turn imports, thereby redefining Integers. Hence a newly created instance of Integers is another one than the first one. This causes my tests to break.

This problem does not arise when I work in the SageMath shell/console. I read two little paragraphs in the SageMath documentation suggesting that I should do something like the following in the doctests of for example my division function in

import __main__
__main__.Integers = Integers

But I got no success with this. Also I do not fully understand what this does.

I tried looking at the actual SageMath library files which implement integers/rational numbers. But there the files seem to me like they import from their C or Cython versions, which I have no experience with and do not use myself.

Does anybody know a clean way to get rid of this problem?