Mutually referencing imports -- impossible?
sjmachin at lexicon.net
Mon Jul 14 01:17:52 CEST 2008
On Jul 14, 5:30 am, John Roth <johnro... at gmail.com> wrote:
> On Jul 13, 11: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.
> > 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
> While it's possible for circular imports to work, it's very dangerous:
> it's not always possible to tell what went wrong without tracking down
> the process of the import step by step. There are more productive ways
> of banging your head against the wall and going insane.
> In your situation, it might be a whole lot easier to extract a common
> superclass that both of your classes could inherit from.
Like the Vehicle class the OP mentioned?
More information about the Python-list