circular imports (don't yell!)

Peter Hansen peter at engcorp.com
Fri Mar 22 22:56:33 EST 2002


jimh wrote:
> 
> We have a scenario where we have (and need) circular imports, that is, A
> imports B imports C imports A.  Now I know there are ways around this, but
> we have external dependencies that make it very difficult to use an
> alternative, so don't be yelling at me about the design ;)

I can't criticize external dependencies that are outside of 
your control, but be careful ignoring suggestions that
you shouldn't have to find a way to handle circular imports.
You'll have to work harder to convince many of us that
there isn't a fairly straight-forward, if non-obvious,
way to get what you want without a true circular import.

> I have whittled the problem down to 3 files:

Thanks for that! :)

Try this instead, and if it isn't acceptable, my suggestion
would be to explain more about the real situation and let
_us_ conclude that you really do, in fact, have to stick
with your circular imports.

a.py
------
consta = 3
if __name__ == "__main__":
    from b import *    # other modules don't run these
    from c import *
    print consta
    print constb
    print constc

> Any ideas?

I didn't bother trying to figure why it works the one way
you had it but doesn't the other way.  You really don't want
to be relying on some obscure phenomenon that takes that 
much effort to investigate, even if you can get it working.

Also, do you realize that "from X import *" is a bad idea
in general?  I'll assume that was just something you did
to try to reproduce the problem in a small sample program...

-Peter



More information about the Python-list mailing list