brython-dev / brython

Brython (Browser Python) is an implementation of Python 3 running in the browser
BSD 3-Clause "New" or "Revised" License
6.37k stars 508 forks source link

Using "dunder methods" for sorting a list of objects #1389

Closed andy31lewis closed 4 years ago

andy31lewis commented 4 years ago

Sorry, here is another one:

class P(object):
    def __init__(self, x):
        self.value = x

    def __eq__(self, other):
        return self.value == other.value

    def __lt__(self, other):
        return self.value < other.value

    def __repr__(self):
        return f"P({self.value})"

a = P(5)
b = P(6)
if a == b: print("a and b are equal")
if a != b: print("a and b are not equal")
if a < b: print("a is less than b")

L = [P(7), P(3), P(5), P(1), P(3)]
L.sort()
print(L)

CPython output:

a and b are not equal
a is less than b
[P(1), P(3), P(3), P(5), P(7)]

Brython output:

a and b are not equal
a is less than b
Traceback (most recent call last):
  File <string>, line 21, in <module>
TypeError: unorderable types: P() <=P()

So Brython is using the "dunder methods" correctly for simple object comparisons, but not for sorting a list of objects. Once again, many thanks in advance, Andy PS thank you for the speedy fix of #1387 !

PierreQuentel commented 4 years ago

Thanks Andy, it was because the implementation used __le__ instead of __lt__ to compare items...