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?
@ 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.
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.
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.
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With