variable scoping across imports?

Hans Nowak wurmy at earthlink.net
Sat Dec 1 15:23:27 EST 2001


Roy Mathew wrote:
> 
> Dear Pythoneers,
> 
> I have what seems to be a vexing problem.
> In its simplest form, here are 2 files
> 
> # ------ file x.py ------------------------------------------------
> z0 = None
> import y
> 
> def set():
>     global z0
>     z0 = 33
> 
> if __name__=='__main__':
>     y.show()
>     set()
>     y.show()
> 
> # ------ file y.py ------------------------------------------------
> import x
> 
> def show():
>     print x.z0
> 
> # -----------------------------------------------------------------
> Now, I would expect that running "python x.py" would produce
>   None
>   33
> but instead, it produces
>   None
>   None
> 
> I have read the rules on variable scoping pretty carefully, I think.
> Are the circular imports confusing python. (BTW, I am using
> "ActivePython 2.1, build 210 ActiveState").
> 
> What am I missing?

Let's see... you start x.py... x imports y... y imports x again...
at that moment x.z0 is None. Now y has a copy of x's namespace with
z0 == None. This is, however, not the same as the global namespace
you're currently in. set() changes z0 to 33, but it does *not*
affect the x module that was imported by y. So I'm afraid you'll
have to think of a different construction.

HTH,

--Hans



More information about the Python-list mailing list