About Modifying Globals

Dave Angel davea at davea.name
Thu Dec 4 18:54:26 EST 2014


On 12/04/2014 03:09 PM, LJ wrote:
> Hi All,
>
> I have a quick question regarding the modification of global variables within functions. To illustrate, consider the following toy example:
>
> a={"1": set()}
> b=9
>
> def gt(l):
>     a["1"] = a["1"] | set([l])
>
> When calling this last function and checking the a dictionary, I get:
>
>>>> gt(5)
>>>> a
> {"1": set([5])}
>
>
> The set in the dictionary was modified. The question is, why isn't it necessary to declare a as global within the gt function, as apposed to a case like
>
> def gt2(l):
>     b=b+l
>
> where I need to declare b as global within the function to avoid:
>
> UnboundLocalError: local variable 'b' referenced before assignment.
>

The reason this sort of thing seems to confuse lots of people is that we 
insist on calling these things assignments.  The thing that's global is 
the name 'a'.  It's global because it's in the global() namespace of 
some module.

The data that's "assigned" to it is an object.  You bind the object to 
the name 'a' with an assignment statement.  If that object is immutable, 
then the only way to change 'a' is to do another assignment.

But if the object is mutable, as a set is, then it can change as much as 
you like without rebinding the name.

A given object may have any number of names bound to it, including no 
names.  An example of that could be objects that are referenced only in 
some list.

Python doesn't have declarations, so when a function is compiled, the 
compiler has to infer what names are to be local and what are not.  The 
rule it normally uses is roughly based on whether an assignment occurs 
somewhere inside the function.


-- 
DaveA



More information about the Python-list mailing list