Curious case of UnboundLocalError

Johannes Bauer dfnsonfsduifb at gmx.de
Fri Mar 30 07:25:28 EDT 2018


On 30.03.2018 13:13, Ben Bacarisse wrote:

>> import collections
>>
>> class Test(object):
>> 	def __init__(self):
>> 		z = {
>> 			"y": collections.defaultdict(list),
> 
> This mention of collections refers to ...
> 
>> 		}
>> 		for (_, collections) in z.items():
> 
> ... this local variable.

Yup, but why? I mean, at the point of definition of "z", the only
definition of "collections" that would be visible to the code would be
the globally imported module, would it not? How can the code know of the
local declaration that only comes *after*?

>> Interestingly, when I remove the class:
> 
> The significant change is removing the function that creates a local scope.

Hmmm yes, there's definitely something that I wasn't aware of when
dealing with local scopes.

>> It works as expected (doesn't throw).
> 
> ... except now collections is bound to a list (from the for) and no
> longer refers to the module.

Yup -- which was why my naming was stupid in the first place. However, I
really wasn't aware of this and was certainly surprised -- even though
the workaround is obvious (just don't call it "collections", duh) I
wanted to investigate.

Thanks for the clarification, most interesting!

Cheers,
Joe

-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa <hidbv3$om2$1 at speranza.aioe.org>



More information about the Python-list mailing list