Defaults, order=True and frozen=True
🌍 In real life. Three everyday ideas fit dataclasses perfectly:
- defaults: at a tea stall, if you don't say otherwise you get a medium cup with one sugar
- order: app versions are compared part by part, so version 1.10 is newer than 1.2 (comparing them as text would get this wrong)
- frozen: a printed receipt can't be changed; if something is wrong, you get a new receipt
@dataclass takes options for the last two: @dataclass(order=True, frozen=True).
The idea in one sentence: dataclass fields can have defaults, order=True writes < and friends by comparing fields in order, and frozen=True makes objects read-only.
Its words:
- default: a field value used when the call leaves it out,
sugar: int = 1 order=True: compare objects field by field, like tuplesfrozen=True: no field can change after the object is madefield(default_factory=list): a fresh list for each object
How each option works, step by step:
order=Truewrites<,<=,>and>=. They compare the fields in the order you wrote them, like comparing(1, 2)with(1, 10): the first fields tie, so the second decides. That also makessorted(),min()andmax()work.frozen=Truemakes every field read-only after the object is made. Changing one raises aFrozenInstanceError.- Defaults work like default parameters: fields with a default must come after the ones without.
from dataclasses import dataclass, field
@dataclass
class TeaOrder:
name: str
size: str = "medium"
sugar: int = 1
extras: list = field(default_factory=list)
a = TeaOrder("Ana")
b = TeaOrder("Bo", "large", 0)
a.extras.append("ginger")
print(a)
print(b)from dataclasses import dataclass
@dataclass(order=True)
class Version:
major: int
minor: int
versions = [Version(1, 10), Version(1, 2), Version(0, 9)]
print(sorted(versions))
print(max(versions))Checking and filling in after __init__: __post_init__. The __init__ a dataclass writes only stores the fields. To check them, or to work out a field from the others, write __post_init__(self): Python calls it straight after. A field marked field(init=False) is left out of the call and filled in there.
Two more options. kw_only=True makes every field keyword-only, so Ticket(route="Dhaka-Sylhet", seat=12) must name each value; a call by position fails with TypeError: Ticket.__init__() takes 1 positional argument but 3 were given. slots=True gives the class __slots__ (Lesson 21.4): less memory, and no misspelt attributes.
from dataclasses import dataclass, field
@dataclass
class Order:
item: str
qty: int
price: float
total: float = field(init=False)
def __post_init__(self):
if self.qty < 1:
raise ValueError("qty must be at least 1")
self.total = self.qty * self.price
print(Order("tea", 3, 15))
try:
Order("tea", 0, 15)
except ValueError as e:
print("refused:", e)
@dataclass(kw_only=True, slots=True)
class Ticket:
route: str
seat: int
print(Ticket(route="Dhaka-Sylhet", seat=12))Why frozen? A value that can't change can be shared safely (nobody can alter your copy) and, because its fields never change, it can be hashed and used in a set or as a dictionary key. A frozen dataclass gets a __hash__ for free.
Mistakes and edge cases.
- Changing a frozen field.
p.x = 2givesdataclasses.FrozenInstanceError: cannot assign to field 'x'. Make a new object instead. - The field order decides the sort. With
order=True, the first field compares first; put the most important field first. - Comparing different classes.
order=Trueonly compares objects of the same class.
Quiz
What does this print?
from dataclasses import dataclass @dataclass class Tea: size: str = "medium" sugar: int = 1 print(Tea(), Tea("small"))What does this print?
from dataclasses import dataclass @dataclass(order=True) class Score: points: int name: str print(Score(5, "Bo") < Score(5, "Cy"), Score(9, "A") < Score(3, "Z"))What happens on
p.x = 5whenpis a@dataclass(frozen=True)?- A FrozenInstanceError: fields can't change
- x becomes 5
- A new object is made
What does this print?
from dataclasses import dataclass, field @dataclass class Cart: items: list = field(default_factory=list) a = Cart() b = Cart() a.items.append("milk") print(a.items, b.items)Which line has a mistake?
from dataclasses import dataclass @dataclass class Tea: size: str = "medium" name: str print(Tea(name="Ana"))What does this print?
from dataclasses import dataclass, field @dataclass class Box: width: int height: int area: int = field(init=False) def __post_init__(self): self.area = self.width * self.height print(Box(3, 4))
Coding tasks
Write a dataclass
TeaOrderwithname(str),size(str, default"medium") andsugar(int, default1).Write a dataclass
Versionwithmajorandminor(int) that can be compared and sorted, soVersion(1, 2) < Version(1, 10)is True.Write a frozen dataclass
Receiptwithshop(str) andtotal(int). Changing a field must raise an error.