'What is the purpose of sort_index of a Dataclass in Python?
I am learning about Dataclasses but I am confused on the purpose of sort_index and how it actually works.
I can't seem to find any valuable information on it. The official Python documentation doesn't mention it, which is mind boggling.
Here is an example:
@dataclass(order=True)
class Person:
sort_index: int = field(init=False, repr=False)
name: str
age: int
weight: int = 190
def __post_init__(self):
self.sort_index = self.weight
So, what is the purpose of sort_index? What is it used for? When do I use it?
Thanks again for taking the time to answer my question. I am new to Python.
Solution 1:[1]
Setting a sort_index
attribute (or indeed, any identifier—the name is irrelevant) in the __post_init__
method appears to be the value on which comparisons are performed.
There is an implicit setting of the comparison methods (__lt__
, __gt__
, etc--read about dunder methods if unfamiliar), using the attributes provided in the __post_init__
method first, and if required, the remaining attributes for resolution.
Class constructor
from dataclasses import dataclass, field
@dataclass(order=True)
class Person:
sort_index: int = field(init=False)
age: int
def __post_init__(self):
self.sort_index = self.age
first example—attribute age
is equal:
>>> p1 = Person(age=10)
>>> p2 = Person(age=10)
>>> p1 == p2
True
Second example—age
is greater:
>>> p1 = Person(age=10)
>>> p2 = Person(age=20)
>>> p2 > p1
True
More complex example:
from dataclasses import dataclass, field
@dataclass(order=True)
class Person:
foo: int = field(init=False, repr=False)
bar: int = field(init=False, repr=False)
name: str
age: int
weight: int = 190
def __post_init__(self):
self.foo = self.weight
self.bar = self.age
>>> p1 = Person('p1', 10)
>>> p2 = Person('p1', 11)
>>> p2 > p2
True
Reasonfoo
(weight
) is equal for both instances, so comparison is done on bar
(age
)
Conclusion
The comparisons can be arbitrarily complex, and identifiers are not important.
I highly recommend this video on dataclasses, by ArjanCodes.
Apart from the video, here's a github link to example dataclass code (from the same video).
Hope this helped—I just learned about dataclasses myself.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | chwi |