Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 206
Jacques de Hooge Avatar asked Apr 16 '18 13:04

Jacques de Hooge


People also ask

What is the use of dataclass in Python?

@ dataclasses. dataclass (*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) ¶ This function is a decorator that is used to add generated special method s to classes, as described below. The dataclass () decorator examines the class to find field s. A field is defined as a class variable that has a type annotation.

Do dataclasses provide enough value in Python TDLR?

Dataclasses in Python 3.7 2019-05-22 python TDLR: Initially, I was interested in the dataclassesfeature that was added to Python 3.7 standard library. However after a closer look, It’s not clear to me if dataclassesprovide enough value. Third-party libraries such as attrsand pydanticoffer considerably more value.

Do Python dataclasses add too much code?

As we’ve seen, python dataclasses fill a niche need to data-classes. Although they are regular classes, it’s highly recommended to keep them as vessels for clean, typed, data, and not add too much code in them. The issue though, is that apart from the dunder function generation, and cleaner-looking code, they don’t seem to provide much.

When were dataclasses added to the Python standard library?

In Python 3.7, dataclasseswere added to the standard library. There’s a terrific talk by Raymond Hettingerthat is a great introduction to the history and design of dataclasses.


1 Answers

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).

like image 150
jonrsharpe Avatar answered Oct 05 '22 22:10

jonrsharpe