Search code examples
pythontranscryptpython-3.7python-dataclasses

Why don't Python 3.7 dataclasses support < > <= and >=, or do they?


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?


Solution

  • 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. If order is true and eq is false, a ValueError is raised.

    So you want @dataclass(order=True).