Are dicts supposed to raise comparison errors
Peter Otten
__peter__ at web.de
Tue Jul 31 05:07:20 EDT 2018
Robin Becker 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.
I disagree. Going from {"a": 1} in Python 2 to {"a": 1, b"a": 2} in Python3
can certainly be a source of nasty bugs.
Also the interpreter cannot magically separate the comparisons directly
"done by you" from those you triggered by running other people's code.
> It's not an error to put 1 and 1.0 and 'a' into a dict.
With these keys you end up with a single entry in both py2 and py3.
> 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?
Not the hash, a collision is basically meaningless unless it causes a
performance regressen. However, ensuring that all keys have the same type
may sometimes be useful.
More information about the Python-list
mailing list