Sorting objects: order=True
By default, < and > do not work with dataclasses. With order=True, Python compares the objects attribute by attribute, in the order in which they are declared, just as tuples are compared:
from dataclasses import dataclass
@dataclass(order=True)
class Player:
points: int
name: str
a = Player(50, "ana")
b = Player(80, "luis")
c = Player(80, "eva")
print(a < b) # True (50 < 80)
print(b > c) # True (equal points; "luis" > "eva")
ranking = sorted([a, b, c], reverse=True)
print([p.name for p in ranking]) # ['luis', 'eva', 'ana']
That is why the order of the attributes matters: the first one is the main criterion. Practice with Ranking with sortable dataclasses.
Sorting by another criterion
If you do not want the dataclass to be sortable, use sorted with key, as with any object:
@dataclass
class Person:
name: str
age: int
people = [Person("Ana", 30), Person("Luis", 25), Person("Eva", 41)]
by_age = sorted(people, key=lambda p: p.age)
print([p.name for p in by_age]) # ['Luis', 'Ana', 'Eva']
Immutable: frozen=True
With frozen=True, the attributes cannot be modified after creating the object. If you try, FrozenInstanceError is raised:
from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True)
class Coordinate:
lat: int
lon: int
c = Coordinate(10, 20)
try:
c.lat = 0
except FrozenInstanceError:
print("Cannot be modified") # Cannot be modified
An immutable object is safer: nobody can change it by accident, and it can also be used as a dictionary key or as an element of a set:
visited = {Coordinate(1, 1), Coordinate(2, 2), Coordinate(1, 1)}
print(len(visited)) # 2 (the repeated one counts only once)
replace: creating a modified copy
Since it cannot be changed, to "modify" an immutable object you create a new one with dataclasses.replace:
from dataclasses import replace
c = Coordinate(10, 20)
new = replace(c, lat=c.lat + 1)
print(c) # Coordinate(lat=10, lon=20)
print(new) # Coordinate(lat=11, lon=20)
Practice with Immutable dataclass.
Converting to a dictionary or tuple
from dataclasses import asdict, astuple
c = Coordinate(10, 20)
print(asdict(c)) # {'lat': 10, 'lon': 20}
print(astuple(c)) # (10, 20)
asdict is very useful for saving an object as JSON, for example with json.dumps(asdict(c)).
Comparison with other options
| Tuple | Dictionary | Normal class | Dataclass | |
|---|---|---|---|---|
| Access by name | No | With brackets | With a dot | With a dot |
| Can be modified | No | Yes | Yes | Yes (or not with frozen) |
| Type checking | No | No | No | Annotations |
| Code needed | Very little | Little | A lot | Little |