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

John Roth newsgroups at jhrothjr.com
Fri Jul 29 08:42:21 EDT 2005


<seberino at spawar.navy.mil> wrote in message 
news:1122616696.886226.279510 at f14g2000cwb.googlegroups.com...
> 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.

Actually, you don't need a "global foo" statement to
_access_ the value. You do need a "global foo" to
_rebind_ the value.

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

Telling an object to mutate itself doesn't rebind the object.
so, if you wanted to say:

foo = 5

and have it work at the module level, you'd need a global foo
statement, while

foo["bar"] = "spam"

doesn't. The dictionary "foo" isn't rebound, all that's happening
is that its state is being changed (that is, the key and value is
being added to the dictionary).

HTH

John Roth

>
> Chris
> 




More information about the Python-list mailing list