About Modifying Globals

Ian Kelly ian.g.kelly at gmail.com
Thu Dec 4 15:21:39 EST 2014


On Thu, Dec 4, 2014 at 1:09 PM, LJ <luisjosenovoa at gmail.com> 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.

https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

In the first case, you never assign to a; you only modify it. Since it's
never assigned locally the compiler knows it can't be a local variable, so
it automatically makes it a global.

In the second case, the assignment to b causes the compiler to treat the
variable as local by default, so it needs to be explicitly marked as global.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20141204/03461906/attachment.html>


More information about the Python-list mailing list