Addind imports to a class namespace
Peter Otten
__peter__ at web.de
Sat Jul 11 10:39:13 EDT 2009
Ryan K wrote:
> I'm thinking that perhaps this isn't a circular import and that I
> don't understand importing. Here is a better explanation of my case (I
> am using Django):
>
> I have file x.py that declares classes A, B, C.
Classes in Python are executable code, just like import-statements. That's
why there is no Python equivalent to forward declarations in other
languages; every name has to be known at the point where it occurs in the
module.
> There is also a file y.py that contains two methods T, U and the class
> that we are talking about above.
>
> x.py uses a dispatcher system to connect a signal to methods T and U
> in y.py so it does: from y import T, U.
>
> y.py needs to use classes A, B, C which is basically Menu and Link
> (and some other class) above so I am thinking that if in y.py I have
> from x import A, B, C that will cause a circular import?
Yes. Having x import y and y import x creates a cycle. If you cannot avoid
this by moving to a simpler design you can always introduce a third module z
that imports x and y, and then explicitly resolves the circular references.
> Is this not correct and if it isn't can you explain why? Does using
> from ... import X, Y, Z, i.e. explicit imports avoid this problem or
> does it exacerbate it?
It has no effect.
from module import X
is equivalent to
import module
X = module.X
del module # just the name, not the module itself
Peter
More information about the Python-list
mailing list