Strange effect with import

Peter Otten __peter__ at web.de
Thu Dec 20 16:11:37 EST 2012


Jens Thoms Toerring wrote:

> Hi,
> 
>    I hope that this isn't a stupid question, asked already a
> hundred times, but I haven't found anything definitive on
> the problem I got bitten by. I have two Python files like
> this:
> 
> -------- S1.py ------
> import random
> import S2
> 
> class R( object ) :
>     r = random.random( )
> 
> if __name__ == "__main__" :
>     print R.r
>     S2.p( )
> 
> -------- S2.py ------
> import S1
> 
> def p( ) :
>     print S1.R.r
> 
> and my expectation was that the static variable 'r' of class
> R would be identical when accessed from S1.py and S2.py.
> Unfortunately, that isn't the case, the output is different
> (and R seems to get instantiated twice).
> 
> But when I define R in S2.py instead
> 
> -------- S1.py ------
> import S2
> 
> print S2.R.r
> S2.p( )
> 
> -------- S2.py ------
> import random
> 
> class R( object ) :
>     r = random.random( )
> 
> def p( ) :
>     print R.r
> 
> or, alternatively, if I put the defintion of class R into
> a third file which I then import from the other 2 files,
> things suddenly start to work as expected/ 

That's the correct approach.

> Can someone
> explain what's going one here? I found this a bit sur-
> prising.

You should never import your program's main module anywhere else in the 
program. When Python imports a module it looks it up by the module's name in 
the sys.modules cache. For the main script that name will be "__main__" 
regardless of the file's actual name, so a subsequent "import S2" will 
result in a cache miss and a new module instance.

Similar problems occur when there is a PYTHONPATH pointing into a package 
and you have both

import package.module

and

import module

Again you will end up with two module instances, one called 
"package.module", the other just "module".

> This is, of course, not my "real" code - it would be much
> more sensible to pass the number to the function in the
> second file as an argument - but is the smallest possinle
> program I could come up with that demonstrate the prob-
> lem. In my "real" code it's unfortunately not possible
> to pass that number to whatever is going to use it in the
>  other file, I have to simulate a kind of global variable
> shared between different files.






More information about the Python-list mailing list