[Tutor] import question

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 4 Jul 2001 12:26:19 +0200


On  0, Glen Wheeler <wheelege@tsn.cc> wrote:
>   Hey Tutorians,
> 
>   I've got a little query regarding importing.  Say I've got several modules, one main module and the others are specific functional modules.
>   My problem is that I have a few classes defined in the main module, and these are useful to all the auxilary modules.  The badness?  Python spews when I try to do it.  In fact, I get very weird results.
> 
> ###mainmodule###
> import aux1,aux2,aux3
> 
> #--code--#
> 
> ###aux1###
> from mainmodule import uniclass
> 
> #--code--#
> 
> and when I try to run mainmodule pythonwin spits with an error in aux1 -
> saying mainmodule has no attribute uniclass, which is just wrong.  If I run
> it again then it dies when I try to use a class from aux1 (or any of the
> other modules), which makes sense if the original import died.

Look closely what happens: in the main module, you do the import *before*
your class definitions. So *at the time the aux1 module is run*, uniclass
doesn't exist yet!

Usually, you can solve this though by doing the imports in the main module
at the bottom of the file, when the classes have already been defined.

Also, in many cases not using "from...import" works, because the class is
only used inside of functions, so it's only looked up when the function is
run. Lots of problems can be avoided by never using "from...import" :-)

Generally "circular imports" are a bit dodgy and sometimes a sign of bad
design, at least, I often have the feeling that there's a cleaner design
lurking just outside my range of thought somewhere.

"Learning Python" has a nice explanation of this phenomenon under "Module
Gotchas", and their advice is basically: "Don't do that...really!" :-).
Redesigning helps.

-- 
Remco Gerlich