About Modifying Globals

Chris Angelico rosuav at gmail.com
Thu Dec 4 15:22:15 EST 2014


On Fri, Dec 5, 2014 at 7:09 AM, LJ <luisjosenovoa at gmail.com> wrote:
> def gt(l):
>    a["1"] = a["1"] | set([l])
>
>
> def gt2(l):
>    b=b+l

These two may both look like they're assigning something, but one of
them is assigning directly to the name "b", while the other assigns to
a subscripted element of "a". In the first function, "a" is still the
same object after the change; in the second, "b" has been replaced by
a new object. That's why your second one needs a global declaration.
It's all about names and assignment; if you're not assigning to the
actual name, there's no need to declare where the name comes from,
because you're only referencing it, not replacing it.

ChrisA



More information about the Python-list mailing list