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

Curious case of UnboundLocalError

On 30.03.2018 13:25, Johannes Bauer wrote:

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

Now that I understand what's going on, this is a much clearer example:

import collections
def foo():
	collections = "BAR"

I would have thought that during the "print", collections (because
locally undefined) would expand the scope to global scope and refer to
the module and only after the definition overwrites the binding with the
local scope, collections would be "BAR".

But that's not the case. Huh! I wonder if I'm the last one to notice
that -- it's never come up before for me, I think :-)


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