Circular imports in Python

I have to say that this restriction has bitten me so many times now and it's one lame restriction.

Basically, Python has an awful support for circular imports, a simple example:

# a.py
import b
x = 1

# b.py
import a
x = a.x + 1 #circular definition, x isn't defined

Now I understand why it's like this (Python is very dynamic and import is a executable statement yada yada), but a lot of times it's just useful for two modules to reuse each others code. Here are some examples of this:

  • Cache + Model code: Cache uses model and model has to invalidate cache on updates
  • Worker + Model: Model adds tasks to a worker (i.e. uses worker) and worker reuses code from model
  • Users + Items: Items uses Users code (such as getUserById) and Users reuses Items code (such as deleteItems(uid))

Now a solution for this could be to create more modules or do some hacks, but generally, I really hope they solve this issue since it's really annoying and prevents some designs.

Circular imports are solved in languages such as Perl or Java.

Code · Python 8. Sep 2008
© Amir Salihefendic. Powered by Skeletonz.