1

Possible Duplicate:
Python: Circular (or cyclic) imports
Circular dependency in Python

I have a Python package featuring two modules that import each other. That is, in module A we have the line

from B import b

and in module B we have the line

from A import a

When I try to load the package containing these modules I get the following error

ImportError: cannot import name a

Is there a way to avoid this error (without combining the two modules into one big module AB)?

Community
  • 1
  • 1
bandini
  • 145
  • 5
  • Yes, you're right. I missed that one when I was searching previously answered questions. Thanks – bandini Feb 17 '12 at 16:38

2 Answers2

3
  1. Split them up into even more modules -- for example you can factor out a into a module of its own that both A and B depend on.

  2. Use import A and import B instead of the from ... variants -- this will make the imports succeed even if the name you want to import has not yet been bound at the time of the import.

  3. Use function level imports at the specific places you need the symbols from the other module. (I don't like this option too much, but it works.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
0

You can't do that because you have a circular reference. Create a new module and import both there:

from B import b
from A import a
Lipis
  • 21,388
  • 20
  • 94
  • 121