Curious case of UnboundLocalError

Johannes Bauer dfnsonfsduifb at gmx.de
Fri Mar 30 06:24:47 EDT 2018


Hey group,

I stumbled about something that I cannot quite explain while doing some
stupid naming of variables in my code, in particular using "collections"
as an identifier. However, what results is strange. I've created a
minimal example. Consider this:

import collections

class Test(object):
	def __init__(self):
		z = {
			"y": collections.defaultdict(list),
		}
		for (_, collections) in z.items():
			pass

Test()


In my opinion, this should run. However, this is what happens on Python
3.6.3 (default, Oct  3 2017, 21:45:48) [GCC 7.2.0] on linux):

Traceback (most recent call last):
  File "x.py", line 11, in <module>
    Test()
  File "x.py", line 6, in __init__
    "y": collections.defaultdict(list),
UnboundLocalError: local variable 'collections' referenced before assignment

Interestingly, when I remove the class:

import collections

z = {
	"y": collections.defaultdict(list),
}
for (_, collections) in z.items():
	pass

It works as expected (doesn't throw).

Have I found a bug in the interpreter or am I doing something incredibly
stupid? I honest cannot tell right now now.

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