module variable scope

Stefan Quandt squan at web.de
Thu Oct 30 06:58:49 EST 2003


Alex Martelli <aleax at aleax.it> wrote in message news:<K9Mnb.371607$R32.12308846 at news2.tin.it>...
> Stefan Quandt wrote:
> 
> > "Batista, Facundo" <FBatista at uniFON.com.ar> wrote in message
> > news:<mailman.170.1067348898.702.python-list at python.org>...
> >> > I expected variable v to be changed by calling setv() but it is not.
> >> > Who can explain this?
> >> 
> >> No, because you're creating a new 'v' variable in the *local* scope of
> >> 'setv'.
> > So how can I access the global module variable v within function
> > setv() (like getv() does automatically)?
> 
> Accessing is easy, but you're talking about re-binding, which is
> quite a different thing.
> 
> Integers (and floats, strings, tuples) are immutable.  So, there
> is no way you can mutate the object to which name 'v' is bound
> while leaving name v itself alone.  All you can do is to re-bind
> name 'v' -- have it refer to a new and separate object from the
> one it was previously referring to; 
Yes, this is what setv() is intended to do.
But instead of rebinding the existing modules variable v, it assigns a
new local v.
And getv() accesses the global v.
That's confusing.

I could help my self now by using global to force getv() using module
scope/namespace:

<begin a.py>
v = None
def setv( x ):   global v; v = x
def getv():    return v
<end a.py>

<begin b.py>
from a import setv, getv

print getv()
setv( 'hello' )
print getv()
<end b.py>

Regards
  Stefan




More information about the Python-list mailing list