Data Classes — Drill and Exercise Answers#

Drill#

Build positions.py step by step: a frozen Symbol dataclass, a Position dataclass with a derived field, sorting, replace(), and JSON output via asdict().

Step 1 — Frozen Symbol dataclass#

 1from dataclasses import dataclass, field, replace, asdict
 2import json
 3
 4@dataclass(frozen=True)
 5class Symbol:
 6    ticker: str
 7
 8    def __post_init__(self) -> None:
 9        object.__setattr__(self, "ticker", self.ticker.upper())
10
11# Verify normalisation
12s = Symbol("aapl")
13print(s)          # Symbol(ticker='AAPL')
14print(hash(s))    # hashable because frozen=True
Symbol(ticker='AAPL')
-2891670935396007862

frozen=True makes Symbol immutable and hashable. Inside __post_init__ we cannot use a plain assignment because __setattr__ has been replaced by the decorator — object.__setattr__ bypasses it to write the uppercased ticker during construction.

Step 2 — Position dataclass with a derived total_cost#

 1@dataclass
 2class Position:
 3    symbol: Symbol
 4    shares: int
 5    cost_basis: float
 6    total_cost: float = field(init=False, repr=True)
 7
 8    def __post_init__(self) -> None:
 9        if self.shares <= 0:
10            raise ValueError(f"shares must be > 0, got {self.shares}")
11        if self.cost_basis <= 0:
12            raise ValueError(f"cost_basis must be > 0, got {self.cost_basis}")
13        self.total_cost = self.shares * self.cost_basis
14
15p = Position(Symbol("AAPL"), 10, 175.50)
16print(p)
Position(symbol=Symbol(ticker='AAPL'), shares=10, cost_basis=175.5, total_cost=1755.0)

total_cost is declared with field(init=False) so it is excluded from __init__ — callers cannot supply it. __post_init__ validates the other fields and then computes total_cost from shares * cost_basis.

Step 3 — Create three positions and sort by total_cost descending#

1positions = [
2    Position(Symbol("AAPL"), 50, 189.45),
3    Position(Symbol("MSFT"), 30, 415.00),
4    Position(Symbol("TSLA"), 20, 248.75),
5]
6
7for p in sorted(positions, key=lambda p: p.total_cost, reverse=True):
8    print(f"{p.symbol.ticker:6s}  shares={p.shares:4d}  cost_basis=${p.cost_basis:8.2f}  total=${p.total_cost:10.2f}")
MSFT    shares=  30  cost_basis=$  415.00  total=$  12450.00
AAPL    shares=  50  cost_basis=$  189.45  total=$   9472.50
TSLA    shares=  20  cost_basis=$  248.75  total=$   4975.00

Step 4 — Use replace() to increase share count#

1aapl = positions[0]
2aapl_updated = replace(aapl, shares=100)
3
4print(f"Original : shares={aapl.shares:4d}  total_cost=${aapl.total_cost:.2f}")
5print(f"Updated  : shares={aapl_updated.shares:4d}  total_cost=${aapl_updated.total_cost:.2f}")
Original : shares=  50  total_cost=$9472.50
Updated  : shares= 100  total_cost=$18945.00

dataclasses.replace() constructs a new Position with shares=100 and all other fields copied from aapl. Because the new instance goes through __init__, __post_init__ re-runs and recomputes total_cost — so it reflects the updated share count automatically.

Step 5 — JSON output with asdict()#

1for p in positions:
2    print(json.dumps(asdict(p), default=str))
{"symbol": {"ticker": "AAPL"}, "shares": 50, "cost_basis": 189.45, "total_cost": 9472.5}
{"symbol": {"ticker": "MSFT"}, "shares": 30, "cost_basis": 415.0, "total_cost": 12450.0}
{"symbol": {"ticker": "TSLA"}, "shares": 20, "cost_basis": 248.75, "total_cost": 4975.0}

asdict() recurses into the nested Symbol dataclass, converting it to {"ticker": "AAPL"}. default=str is passed to json.dumps as a safety net for any non-serialisable types (e.g., datetime objects) — not needed here but a useful habit.


Exercise 1 — Convert a Manual Class#

Convert BankAccount to a @dataclass, preserving: balance defaults to 0.0, _count tracks total accounts created, and equality is based solely on account_id.

 1from dataclasses import dataclass, field
 2from typing import ClassVar
 3
 4@dataclass
 5class BankAccount:
 6    account_id: str
 7    holder: str
 8    balance: float = 0.0
 9
10    # ClassVar fields are excluded from __init__, __repr__, and __eq__
11    _count: ClassVar[int] = 0
12
13    def __post_init__(self) -> None:
14        BankAccount._count += 1
15
16    def __eq__(self, other: object) -> bool:
17        if not isinstance(other, BankAccount):
18            return NotImplemented
19        return self.account_id == other.account_id
20
21    def __hash__(self) -> int:
22        return hash(self.account_id)
23
24
25a1 = BankAccount("ACC-001", "Alice", 1000.0)
26a2 = BankAccount("ACC-002", "Bob")
27a3 = BankAccount("ACC-001", "Alice (duplicate)", 500.0)
28
29print(a1)
30print(a2)
31print(f"a1 == a3: {a1 == a3}")          # True  — same account_id
32print(f"a1 == a2: {a1 == a2}")          # False
33print(f"Total accounts: {BankAccount._count}")  # 3
BankAccount(account_id='ACC-001', holder='Alice', balance=1000.0)
BankAccount(account_id='ACC-002', holder='Bob', balance=0.0)
a1 == a3: True
a1 == a2: False
Total accounts: 3

Key decisions:

  • _count is a ClassVar[int] — this tells @dataclass to skip it entirely (not in __init__, not in __repr__, not in the default __eq__), and mypy enforces that it is only assigned through the class.

  • __post_init__ increments _count on every construction, matching the original behaviour.

  • A custom __eq__ replaces the generated one so equality is based solely on account_id. When you define __eq__, Python sets __hash__ to None by default, so we also define __hash__ to keep instances hashable.


Exercise 2 — Validation and Derived Fields#

Build a frozen OptionContract dataclass with validation and an is_in_the_money() method.

 1import datetime
 2from dataclasses import dataclass
 3
 4@dataclass(frozen=True)
 5class OptionContract:
 6    ticker: str
 7    strike: float
 8    expiry: datetime.date
 9    option_type: str        # "CALL" or "PUT" (normalised in __post_init__)
10    premium: float
11
12    def __post_init__(self) -> None:
13        # Normalise and validate option_type
14        object.__setattr__(self, "option_type", self.option_type.upper())
15        if self.option_type not in {"CALL", "PUT"}:
16            raise ValueError(f"option_type must be 'CALL' or 'PUT', got {self.option_type!r}")
17        if self.strike <= 0:
18            raise ValueError(f"strike must be > 0, got {self.strike}")
19        if self.premium < 0:
20            raise ValueError(f"premium must be >= 0, got {self.premium}")
21
22    def is_in_the_money(self, spot_price: float) -> bool:
23        """Return True if the option has intrinsic value at the given spot price."""
24        if self.option_type == "CALL":
25            return spot_price > self.strike
26        return spot_price < self.strike  # PUT
27
28
29call = OptionContract("AAPL", strike=190.0, expiry=datetime.date(2025, 12, 19), option_type="call", premium=5.50)
30put  = OptionContract("AAPL", strike=190.0, expiry=datetime.date(2025, 12, 19), option_type="PUT",  premium=4.20)
31
32print(call)
33print(f"CALL ITM at $195: {call.is_in_the_money(195.0)}")   # True
34print(f"CALL ITM at $185: {call.is_in_the_money(185.0)}")   # False
35print(f"PUT  ITM at $185: {put.is_in_the_money(185.0)}")    # True
36print(f"PUT  ITM at $195: {put.is_in_the_money(195.0)}")    # False
37
38# Verify normalisation
39print(f"option_type normalised: {call.option_type!r}")       # 'CALL'
40
41# Verify hashability (frozen=True)
42contracts = {call, put}
43print(f"In a set: {len(contracts)} contracts")
OptionContract(ticker='AAPL', strike=190.0, expiry=datetime.date(2025, 12, 19), option_type='CALL', premium=5.5)
CALL ITM at $195: True
CALL ITM at $185: False
PUT  ITM at $185: True
PUT  ITM at $195: False
option_type normalised: 'CALL'
In a set: 2 contracts

Because OptionContract is frozen, we must use object.__setattr__ to normalise option_type to uppercase — a plain self.option_type = ... would raise FrozenInstanceError. Validation happens in the same __post_init__ call, after normalisation, so "call" and "CALL" are both accepted.


Exercise 3 — Hierarchy and Structured Logging#

Build BaseReport, VaRReport, and StressReport with a derived risk_level field, then log them as structured JSON.

 1import logging
 2import json
 3import sys
 4from dataclasses import dataclass, field, asdict
 5
 6logging.basicConfig(
 7    level=logging.INFO,
 8    format="%(asctime)s | %(levelname)-8s | %(message)s",
 9    stream=sys.stdout,
10    force=True,
11)
12logger = logging.getLogger(__name__)
13
14
15def _risk_level(ratio: float) -> str:
16    if ratio > 0.05:
17        return "HIGH"
18    if ratio > 0.02:
19        return "MEDIUM"
20    return "LOW"
21
22
23@dataclass
24class BaseReport:
25    report_id: str
26    portfolio_value: float
27
28
29@dataclass
30class VaRReport(BaseReport):
31    var_95: float = 0.0
32    risk_level: str = field(init=False, repr=True)
33
34    def __post_init__(self) -> None:
35        self.risk_level = _risk_level(self.var_95 / self.portfolio_value)
36
37
38@dataclass
39class StressReport(BaseReport):
40    scenario: str = ""
41    loss_amount: float = 0.0
42    risk_level: str = field(init=False, repr=True)
43
44    def __post_init__(self) -> None:
45        self.risk_level = _risk_level(self.loss_amount / self.portfolio_value)
46
47
48var_report    = VaRReport(report_id="VAR-2025-Q4", portfolio_value=1_000_000, var_95=62_000)
49stress_report = StressReport(report_id="STR-2025-Q4", portfolio_value=1_000_000,
50                              scenario="2008-crisis", loss_amount=18_000)
51
52for report in (var_report, stress_report):
53    logger.info(json.dumps(asdict(report)))
54
55print()
56print(f"VaR risk_level   : {var_report.risk_level}")     # HIGH  (62k/1M = 6.2%)
57print(f"Stress risk_level: {stress_report.risk_level}")  # LOW   (18k/1M = 1.8%)
2026-06-20 19:33:39,510 | INFO     | {"report_id": "VAR-2025-Q4", "portfolio_value": 1000000, "var_95": 62000, "risk_level": "HIGH"}
2026-06-20 19:33:39,510 | INFO     | {"report_id": "STR-2025-Q4", "portfolio_value": 1000000, "scenario": "2008-crisis", "loss_amount": 18000, "risk_level": "LOW"}
VaR risk_level   : HIGH
Stress risk_level: LOW

Key points:

  • risk_level is declared with field(init=False) in each subclass so callers cannot supply it; it is always computed by __post_init__.

  • Both subclasses give var_95 / scenario / loss_amount default values (0.0 / "") so the field ordering rule is satisfied — no non-default child field follows a default parent field.

  • _risk_level() is a plain module-level helper rather than a method because the logic is identical in both subclasses and does not depend on self.

  • asdict() flattens the inherited fields from BaseReport alongside the subclass fields into a single dict, which is then serialised as one line of JSON per report.