import order or cross import

Roland Hedberg roland.hedberg at adm.umu.se
Wed Jan 3 06:09:11 EST 2007


Duncan Booth wrote:

> 
> Remember that all statements in Python are executed at the time they are 
> encountered: there are no declarations (apart from 'global') so no looking 
> ahead to see what classes or functions are coming up.

Yes, I've seen this time and time again.

> One other complication in your particular instance: when you run a ONE.py 
> as a script the script is loaded in a module called '__main__', so 'import 
> ONE' will actually load a separate module which is NOT the same as the 
> __main__ module. Likewise when you run TWO.py as a script you have three 
> modules __main__ (loaded from TWO.py), ONE, and TWO.

Hmm, that's interesting.

> 
> The fix in this sort of case is usually to extract the base class out to a 
> third module. If you put BaseColor in base.py then you can safely import 
> that anywhere you want it.

OK, so I'll go for this option. Takes some more intelligence in the
marshalling code but it should be doable.

> An alternative in this case would be to edit ONE.py and move the line 
> 'import TWO' down below the definition of BaseColor: nothing before that 
> actually requires TWO to have been imported yet.

Since no person is involved, in creating files like ONE.py and TWO.py,
this also has to be done by the marshalling code.
I've no clear idea which alternative would be best/easiest but your
first one seems clearer.

> However, you really should try to separate scripts from modules otherwise 
> the double use as both __main__ and a named module is going to come back 
> and bite you.

Oh, that was only there as an example, so you could see the intent usage.

Thanks Duncan!

-- Roland



More information about the Python-list mailing list