[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Curious case of UnboundLocalError

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!


>> 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>