[Python-Dev] Dicts are broken Was: unicode hell/mixing str and unicode asdictionarykeys

Michael Chermside mcherm at mcherm.com
Fri Aug 4 14:26:52 CEST 2006


I'm changing the subject line because I want to convince everyone that
the problem being discussed in the "unicode hell" thread has nothing
to do with unicode and strings. It's all about dicts.

I have not observed real breakage in my own code, but I will present
a sample of made-up-but-completely-reasonable code that works in
2.4, fails in 2.5, and arguably ought to work fine. I think we should
restore the behavior of dicts that when they compare keys for
equality they suppress exceptions (treating the objects as unequal),
or at LEAST retain the behavior for one more release making it a
warning this time.

Here is my sample code:

----------- problem_with_dicts.py ----------
# A sample program to demonstrate that the proposed behavior
# of dicts in Python 2.5 generates bugs. This is not code from
# an actual program, but it is completely reasonable.

# First import from
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486
# the only 5-star recipe in the Python Cookbook for implementing
# enums.
import cookbookenum

# Then set up some reasonable enums. We'll say we're writing
# a program for dealing with dates.
DaysOfWeek = cookbookenum.Enum(
     'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
Months = cookbookenum.Enum(
     'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug',
     'Sep','Oct','Nov','Dec')

# Let's say we also do some translations. Here is a
# useful dictionary:
translations = {}
# which we populate with values
translations[ DaysOfWeek.Mon ] = {
     'en': 'Monday',
     'es': 'Lunes',
     'fr': 'Lundi',
     }
# and assume we do the other days
translations[ Months.Jan ] = {
     'en': 'January',
     'es': 'Enero',
     'fr': 'Janvier',
     }
# and assume we do the other months

# ...then later in the code we could do things like this:
language = 'en'
dayOfWeek = DaysOfWeek.Mon
month = Months.Jan
dayOfMonth = 3
print '%s, %s %s' % (
     translations[dayOfWeek][language],
     translations[month][language],
     dayOfMonth)

# this works in 2.4 but fails in 2.5
--------- end problem_with_dicts.py --------

Please reconsider.

-- Michael Chermside



More information about the Python-Dev mailing list