[Tutor] Question about 'scopes'

alan.gauld@bt.com alan.gauld@bt.com
Tue Mar 25 08:48:26 2003


> assign a value to a variable outside the local namespace (which would 
> normally create a new local variable), ... ", could you 
> explain how assigning a value to something outside of the 
> local scope creates a new *local* variable 

Its because you are assigning the value to a name. In Python 
that's how you create a new variable. Thus by the act of assignment 
you create a new local variable, that's just how Python works, 
it's the rule.

When you want to break the normal mode of operation you have to 
explicitly tell Python to ignore the usual rule and use the 
existing global varable.

An example:

#######
x = 5  # create a global variable by assigning value 5

def f():   # create a new function with its own local scope
   print x    # we don't assign to x so it uses the existing global one

def g():  # another new function with its own scope
   x = 42   # we assign 42 to the name 'x' so python creates a new object
   print x

def h():  # yet another function with its local scope
   global x   # we tell python to use the global one
   x = 101   # this time assignment is to global x
   print x

print x  # --> 5
f()      # --> 5, f() uses the global value
print x  # --> yep, still 5
g()      #--> 42, using local x this time
print x  # still 5, g() didn't change it
h()      # --> 101, assigned by h()
print x  # --> 101, h() changed the global value.

> is that because the value was assigned from *within* the local 
> namespace (i.e. referenced from within the local namespace 
> making it a local variable), 

Yes

> even though the referand (or the object being assigned a value) 
> 'actually' is a global (or non-local) object?

No, its a new object in the local scope created by Pythons normal 
rule of "assignment generates a new object"

> Is this on the right track, or have I lost the plot?

Very close. Recall that Python does not require you to declare 
object up front so it must have some riule for when to create 
new ones. It just so happens that Guido chose assignment as 
the trigger. Thus when you want to assign to an existing object 
which is outside your current scope(either global or in a 
separate module) we must provide a mechanism to make it clear. 
In the case of global we use the keyword 'global' and in the 
case of modules we prefix the name with the module name:

sys.exit()


for example.

HTH,

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/