Sub topic 2
Fine-Tuning Python Dataclass Fields
Assume you know how to define Python classes, use type annotations, and distinguish mutable from immutable objects. This chapter focuses on controlling generated methods and initialization behavior.
Fine-tuning fields with `field()`
The field() function configures one dataclass field. Its options can change whether the field appears in the constructor, representation, and comparisons.
from dataclasses import dataclass, field
@dataclass
class Report:
title: str
pages: int
internal_id: str = field(
repr=False,
compare=False
)
summary: str = field(init=False)
def __post_init__(self):
self.summary = f"{self.title} ({self.pages} pages)"
report = Report("Python Basics", 12, "r-104")
print(report) # Report(title='Python Basics', pages=12, summary='Python Basics (12 pages)')Here, internal_id is required by __init__, but repr=False hides it from printed output. compare=False excludes it from equality checks. summary is excluded from __init__ because the class computes it later.
Use default_factory when each instance needs a fresh mutable value, such as a list or dictionary.
Validation and derived values with `__post_init__`
__post_init__ runs immediately after the generated __init__. Use it to validate related fields or calculate values from them.
from dataclasses import dataclass, field
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width < 0 or self.height < 0:
raise ValueError("dimensions must be non-negative")
self.area = self.width * self.height
print(Rectangle(3, 4)) # Rectangle(width=3, height=4, area=12)The initialization flow is:
`InitVar`: arguments that are not stored
An InitVar is accepted by the generated constructor and passed to __post_init__, but it is not retained as a dataclass field.
from dataclasses import dataclass, field, InitVar
@dataclass
class User:
name: str
password: InitVar[str]
password_length: int = field(init=False, repr=False)
def __post_init__(self, password):
if len(password) < 8:
raise ValueError("password is too short")
self.password_length = len(password)
user = User("Ana", "correct-horse")
print(user) # User(name='Ana')Use InitVar for temporary constructor input, especially when storing the original value would be inappropriate.
Equality and ordering with `eq` and `order`
By default, eq=True makes two instances equal when their comparable fields match. order=True adds <, <=, > and >=, using field order.
from dataclasses import dataclass, field
@dataclass(order=True)
class Priority:
level: int
label: str = field(compare=False)
print(Priority(1, "low") < Priority(2, "high")) # True
print(Priority(1, "low") == Priority(1, "urgent")) # TrueExercise
Which option prevents a field from affecting equality and ordering?
Show answer
Use field(compare=False).