Are dicts supposed to raise comparison errors

Paul Moore p.f.moore at gmail.com
Tue Jul 31 05:01:11 EDT 2018


On 31 July 2018 at 09:32, Robin Becker <robin at reportlab.com> wrote:
> On 31/07/2018 09:16, Paul Moore wrote:
>>
>> On 31 July 2018 at 08:40, Robin Becker <robin at reportlab.com> wrote:
>>>
>>> A bitbucket user complains that python 3.6.6 with -Wall -b prints
>>> warnings
>>> for some reportlab code; the
>>> example boils down to the following
>>>
>>> ##########
>>> C:\code\hg-repos\reportlab\tmp>cat tb.py
>>> if __name__=='__main__':
>>>      d={'a':1}
>>>      d[b'a'] = d['a']
>>> ##########
>>>
>> ..........
>> v.1500 64 bit (AMD64)] on win32
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>>
>>>>> b'a' == 'a'
>>
>> True
>>>>>
>>>>> b'a' == u'a'
>>
>> True
>>>>>
>>>>>
>>
>> which is basically the sort of thing that -b should warn about.
>> Specifically the quoted code would end up with a dictionary with 2
>> entries on Python 3, but 1 entry on Python 2.
>>
>> Paul
>>
> yes but I didn't do the compare so this warning seems entirely spurious and
> wrong. It's not an error to put 1 and 1.0 and 'a' into a dict. Should I get
> a warning if the hashes of two different types happen to clash so that an
> int needs to be checked against a string?

No, but it does seem reasonable (to me, at least) that you'd get a
warning if the behaviour of

a[1] = 12
a[1.0] = 99

were to change so that the dict had two separate entries. That's
exactly what happened here - Python 3 behaves differently than Python
2, and the -b flag is to enable warnings about such cases.

If you feel the warning is spurious then you can simply not use -b. Or
suppress the warning, I guess. But it seems to me that it's an opt-in
warning of something that could cause problems, so I don't really see
why it's such a big problem.

Paul


More information about the Python-list mailing list