Advanced Python / Data Classes

Advanced Python / Data Classes#

  1. What three methods does @dataclass generate by default?

    __init__, __repr__, and __eq__.

  2. Why does holdings: list = [] raise a ValueError, 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 @dataclass decorator detects mutable defaults and raises ValueError at class creation to prevent this. The correct syntax uses field(default_factory=list):

    from dataclasses import dataclass, field
    
    @dataclass
    class Portfolio:
        holdings: list = field(default_factory=list)
    
  3. 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 ValueError or TypeError for 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 with field(init=False) so they are not accepted as constructor arguments.

  4. What does frozen=True prevent, and what extra capability does it add?

    frozen=True replaces __setattr__ and __delattr__ with versions that raise FrozenInstanceError on 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. (Without frozen=True, @dataclass sets __hash__ to None if eq=True, making instances unhashable by default.)

  5. Why must you use object.__setattr__() inside __post_init__ of a frozen dataclass?

    When frozen=True is set, the decorator replaces __setattr__ with a function that unconditionally raises FrozenInstanceError. 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())
    
  6. 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 TypeError when the class is defined.

  7. What does dataclasses.asdict() return, and why is it useful with the logging extra= parameter?

    dataclasses.asdict() returns a plain dict mapping 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 an extra= keyword argument that attaches a plain dict of arbitrary fields to the LogRecord. Because asdict() 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))
    
  8. 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)