why functions in modules need 'global foo' for integer foo but not dictionary foo?

Robert Kern rkern at ucsd.edu
Fri Jul 29 02:16:29 EDT 2005


seberino at spawar.navy.mil wrote:
> At top of a module I have an integer like so...
> 
> foo = 4
> 
> In a function in that module I know I need to do 'global foo' to get at
> the value 4.
> ...

You don't. You need the global declaration to *set* the value of "foo" 
in the module's namespace. When getting the value of "foo" within the 
function, if it's not been defined in the function's local namespace, it 
automatically looks in the global namespace with or without the "global 
foo" declaration. When assigning a value to the name "foo" within the 
function, however, without the global declaration, the value will only 
be assigned to the name "foo" within the local namespace.

http://docs.python.org/ref/naming.html

> IIRC, for dictionaries you DO NOT have this issue?
> 
> Why this scope problem with integers but not dictionaries?

I presume you are trying code like the following:

foo = 4
bar = {}

def fun1():
     foo = 5

def fun2():
     bar['baz'] = 4

Since integers are immutable, all that fun1() does is assign 5 to the 
name "foo" within fun1()'s namespace and doesn't touch the module-level 
namespace.

fun2(), on the other hand, only gets the dictionary from the 
module-level namespace with the name "bar". Then it modifies that 
dictionary (since it's mutable). It does not try to assign a new object 
to the name "bar".

I hope that's clear, but I'm pretty tired right now, and it may not be.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list