About Modifying Globals

LJ luisjosenovoa at gmail.com
Thu Dec 4 15:09:39 EST 2014


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.


I apologize if this question has been answered before.

Thank you.



More information about the Python-list mailing list