Curious case of UnboundLocalError

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


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():
	print(collections)
	collections = "BAR"
foo()

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

Cheers,
Johannes

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