Mutually referencing imports -- impossible?

John Machin sjmachin at lexicon.net
Sun Jul 13 19:15:47 EDT 2008


On Jul 14, 3:55 am, Matthew Wilson <m... at tplus1.com> 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.

And they should not import each other.

>
> In the beginning, when all three (Vehicle, Car, and Motorcycle) were
> defined in the same file, everything worked fine.

You seem to have a strange notion of "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.

What is making a file with 3 classes "enormous"?? What is "enormous"?

>
> Any ideas?

*WRONG WAY*
*GO BACK*

Your structure is not only bizarre, it is also (sticking with only 1
letter of the alphabet) a Byzantine, baroque, and broken concept.

Asking us to "pretend that this can't be avoided for now" is asking
us to aid and abet you in creating a meaningless and unmaintainable
monster. Consider adding Truck and Bus subclasses. Will each subclass
instantiate the other 3??? You should be able to add or remove a
subclass without having to modify all other subclasses.

The only rational solution is not to have the subclasses refer to each
other. Tell us *why* you think you need to have Car refer to
Motorcycle and vice versa, and we should be able to help you find a
way out.

Cheers,
John



More information about the Python-list mailing list