For version 3.7.1 of the Transcrypt Python to JavaScript compiler I am currently using the new @dataclass
decorator. I had expected that ==, !=, <, >, >=, <=
would be supported, as per the PEP's abstract, but it doesn't seem to be the case:
from dataclasses import dataclass
@dataclass
class C:
x: int = 10
Some comparisons are not working:
>>> c1 = C(1)
>>> c2 = C(2)
>>> c1 == c2 # ok
False
>>> c1 < c2 # crash
TypeError: '<' not supported between instances of 'C' and 'C'
Why are the comparison operators not supported, except for ==
and !=
? Or did I overlook something?
They do, just not by default. Per PEP-557:
The parameters to
dataclass
are:...
order
: If true (the default is False),__lt__
,__le__
,__gt__
, and__ge__
methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. Iforder
is true andeq
is false, aValueError
is raised.
So you want @dataclass(order=True)
.