Mutually referencing imports -- impossible?
Gary Herron
gherron at islandtraining.com
Sun Jul 13 14:16:46 EDT 2008
Matthew Wilson wrote:
> I started off with a module that defined a class Vehicle, and then
> subclasses Car and Motorcycle.
>
> In the Car class, for some bizarre reason, I instantiated a Motorcycle.
> Please pretend that this can't be avoided for now.
>
> Meanwhile, my Motorcycle class instantiated a Car as well.
>
> Then I moved the Car and Motorcycle classes into separate files. Each
> imported the Vehicle module.
>
> Then I discovered that my Car module failed because the global
> Motorcycle wasn't defined. The same problem happened in my Motorcycle
> module. Car and Motorcycle can't both import each other.
>
> In the beginning, when all three (Vehicle, Car, and Motorcycle) were
> defined in the same file, everything worked fine.
>
> I don't know how to split them out in separate files now though and I
> really wish I could because the single file is enormous.
>
> Any ideas?
>
> Matt
>
It is easy for imports to be mutually referencing. This presents no
problem to Python if the importing of one module is interrupted by the
import of another.
However, if one of them imports specific names from a module,
from ABC import abc
or
from ABC import *
then it's possible that the (interrupted) import of module ABC has not
progressed to the point that abc is defined.
The solution: Just
import ABC
and later reference ABC.abc
That being said, it is still a good design practice to structure your
modules hierarchically rather than a circularly.
Gary Herron
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list