Curious case of UnboundLocalError

Ben Bacarisse ben.usenet at bsb.me.uk
Fri Mar 30 10:46:28 EDT 2018


Johannes Bauer <dfnsonfsduifb at gmx.de> writes:

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

Why questions can be hard.  The language definition says what's supposed
to happen.  Is that enough of an answer to why?

  4.2.2. Resolution of names
  
  A scope defines the visibility of a name within a block. If a local
  variable is defined in a block, its scope includes that block. [...]

<snip>
-- 
Ben.



More information about the Python-list mailing list