variable scoping across imports?
Roy Mathew
roymath at yahoo.com
Sun Dec 2 16:09:29 EST 2001
"Fredrik Lundh" <fredrik at pythonware.com> wrote in message > more here:
> ...
> http://effbot.org/guides/import-confusion.htm
>
> </F>
Folks,
Thanks for the responses; Fredrik Lundh's response was the most
helpful. From the URL resource he references, I realized that there
are actually 3 imports going on, and not just 2 as one would initially
assume. They are:
"x.py" as __main__
"x.py" as x
"y.py" as y
Hence, there really are 2 "z0" variables alive; one belonging
to the __main__ namespace and the other belonging to the "x"
namespace. Thanks for the nice clear explanation, Fredrik.
By rearranging things thus, I am able to get what I expected.
Incidentally the whole motivation for this scheme was to
simulate "class" variables - ie: have "z0" act as a static
variable.
# ------ file x.py ------------------------------------------------
z0 = None
import y
def set():
global z0
z0 = 33
# ------ file y.py ------------------------------------------------
import x
def show():
print x.z0
# ------ file z.py ------------------------------------------------
import x, y
y.show()
x.set()
y.show()
# -----------------------------------------------------------------
Now, running "python z.py" yields what I had wanted.
Thanks,
Roy Mathew.
More information about the Python-list
mailing list