Advanced Python / Data Classes#
What three methods does
@dataclassgenerate by default?__init__,__repr__, and__eq__.Why does
holdings: list = []raise aValueError, and what is the correct syntax?Python evaluates default values once at class definition time. Every instance created from the class would share the same list object, so mutating one instance’s list would silently affect all others. The
@dataclassdecorator detects mutable defaults and raisesValueErrorat class creation to prevent this. The correct syntax usesfield(default_factory=list):from dataclasses import dataclass, field @dataclass class Portfolio: holdings: list = field(default_factory=list)
When does
__post_init__run, and what are its two most common uses?__post_init__runs immediately after the generated__init__finishes assigning fields. The two most common uses are:Input validation — inspect field values and raise
ValueErrororTypeErrorfor anything that violates the class’s invariants (e.g.,strike <= 0, invalid enum strings).Derived fields — compute and set fields whose values depend on other fields (e.g.,
total_cost = shares * cost_basis). Derived fields are typically declared withfield(init=False)so they are not accepted as constructor arguments.
What does
frozen=Trueprevent, and what extra capability does it add?frozen=Truereplaces__setattr__and__delattr__with versions that raiseFrozenInstanceErroron any attempt to mutate an attribute after construction, making instances effectively immutable.The extra capability it adds is hashability: the decorator generates a
__hash__method based on all fields, so frozen instances can be used as dictionary keys or placed in sets. (Withoutfrozen=True,@dataclasssets__hash__toNoneifeq=True, making instances unhashable by default.)Why must you use
object.__setattr__()inside__post_init__of a frozen dataclass?When
frozen=Trueis set, the decorator replaces__setattr__with a function that unconditionally raisesFrozenInstanceError. Any plain assignment (self.field = value) inside__post_init__would trigger that overridden__setattr__and fail — even during construction.object.__setattr__(self, "field", value)bypasses the overridden__setattr__and writes directly to the instance’s__dict__, which is the same mechanism the generated__init__uses internally for the primary fields. It is the only sanctioned way to set attributes on a frozen instance after the decorator has been applied.from dataclasses import dataclass @dataclass(frozen=True) class Symbol: ticker: str def __post_init__(self) -> None: object.__setattr__(self, "ticker", self.ticker.upper())
In a data class hierarchy, in what order do parent and child fields appear in
__init__?Parent fields come first, in the order they are declared in the parent class, followed by child fields in the order they are declared in the child class. This mirrors Python’s MRO: the generated
__init__for a subclass accepts(parent_field_1, parent_field_2, ..., child_field_1, child_field_2, ...).One important constraint: a parent field with a default value cannot be followed by a child field without a default, because that would create a positional argument after a keyword-only argument. Violating this rule raises a
TypeErrorwhen the class is defined.What does
dataclasses.asdict()return, and why is it useful with the loggingextra=parameter?dataclasses.asdict()returns a plaindictmapping each field name to its value. The conversion is recursive: nested dataclasses become nested dicts, and lists/tuples/dicts containing dataclasses are also converted.The logging methods (
logger.info(),logger.warning(), etc.) accept anextra=keyword argument that attaches a plain dict of arbitrary fields to theLogRecord. Becauseasdict()produces exactly this format, it lets you log a dataclass as a set of structured, queryable fields with a single call — no manual field extraction required:import logging, json, dataclasses logger = logging.getLogger(__name__) @dataclasses.dataclass class Order: ticker: str shares: int price: float order = Order("AAPL", 50, 189.45) logger.info("Order placed", extra=dataclasses.asdict(order))
What is
dataclasses.replace()used for?dataclasses.replace(instance, **changes)creates a shallow copy of a dataclass instance with selected fields replaced by new values; all unspecified fields are copied from the original. It is the standard way to produce a modified version of a dataclass without mutating the original — and for frozen dataclasses, where direct assignment is impossible, it is the only built-in way to do so.from dataclasses import dataclass, replace @dataclass(frozen=True) class Position: ticker: str shares: int price: float original = Position("MSFT", 100, 415.00) updated = replace(original, shares=150) # ticker and price unchanged print(original) # Position(ticker='MSFT', shares=100, price=415.0) print(updated) # Position(ticker='MSFT', shares=150, price=415.0)