Question about scope

Tim Daneliuk tundra at tundraware.com
Thu Jul 5 17:14:27 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...
> 
> TIA,
> --
> ------------------------------------------------------------------------------
> Tim Daneliuk
> tundra at tundraware.com

Oh, while we're at it, if add the following line at the very start of my code:

MyPrint = print

MyPrint *is* in scope inside of FlagFalse() and can be used just fine.

I guess what I want to know is when globally declared objects are seen inside a function, class, or
block, and when they must be explicitly declared as being global.


Many thanks...
-- 
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com



More information about the Python-list mailing list