Curious case of UnboundLocalError

Chris Angelico rosuav at gmail.com
Fri Mar 30 07:32:19 EDT 2018


On Fri, Mar 30, 2018 at 9:24 PM, Johannes Bauer <dfnsonfsduifb at gmx.de> wrote:
> Hey group,
>
> I stumbled about something that I cannot quite explain while doing some
> stupid naming of variables in my code, in particular using "collections"
> as an identifier. However, what results is strange. I've created a
> minimal example. Consider this:
>
> import collections
>
> class Test(object):
>         def __init__(self):
>                 z = {
>                         "y": collections.defaultdict(list),
>                 }
>                 for (_, collections) in z.items():
>                         pass
>
> Test()
>
>
> In my opinion, this should run.

By which you mean:

In your opinion, the name "collections" should refer to the global
until the corresponding local name is first assigned to.

That's a plausible interpretation, but it isn't the way Python does
things. In the interests of ensuring that blocks of code can be
rearranged without changing scoping rules, Python deems that ANY name
EVER assigned to within a given function is local to that function
(unless declared otherwise, of course). So the name "collections" is
local for the _entire_ function.

ChrisA



More information about the Python-list mailing list