Question about scope

Chris Barker chrishbarker at home.net
Thu Jul 5 17:40:26 EDT 2001


Tim Daneliuk wrote:
> I thought I understood python scoping, but I guess I don't.  Consider this
> code: 

> FALSE = 0
> TRUE = not FALSE
> FLAG = TRUE
> 
> def FlagFalse():
>         FLAG = FALSE
> 
> print str(FLAG)
> FlagFalse()
> print str(FLAG)
> 
> I get:
> 1
> 1
> 
> But I expected:
> 1
> 0
> 
> If I declare FLAG as global in the function, it works properly, of course.
> 
> I thought that python checked local scope for a variable first and if
> it did not find it, it appealed to the local namespace.  What am I missing
> here - it's probably at the end of my nose, but I cannot seem to make sense
> of it...

Actually, it checks local first, but more importantly, you can't
re-assign a global variable in a local scope (without using global). if
you assign to a variable in a function, it is local to that function.
The local version of FLAG has been set to FALSE, not the global one.

When the function is byte compiled, it notices that you have assigned
"FLAG" in your function, so sets it as a local name. That why you get an
error if you try to do this:
>> def FlagFalse():
...     print FLAG
...     FLAG = FALSE
...
>>> FlagFalse()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in FlagFalse
UnboundLocalError: local variable 'FLAG' referenced before assignment
>>>

Essentially you have only read-only access to immutable global
variables. Mutable variables you can change, because you are not
reassigning them, so you could do:
>>> FLAG = [TRUE]
>>> def FlagFalse():
...     FLAG[0] = FALSE
...
>>> FLAG
[1]
>>> FlagFalse()
>>> FLAG
[0]

FLAG is still pointing to the same list, you have just changed the
contents.

-Chris




-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list