osdir.com


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

Curious case of UnboundLocalError


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>