Data Classes#

Every FinTech system is full of value objects — an Order, a Position, a settled Transaction. Writing each one by hand means repeating __init__, __repr__, and __eq__ boilerplate for every class. The dataclasses module (PEP 557, Python 3.7+) auto-generates that plumbing from type-annotated field declarations, leaving you with a full Python class and none of the repetition.

By the end of this notebook, you will be able to:

  • replace boilerplate classes with @dataclass

  • define fields with type annotations and sensible defaults

  • validate inputs and compute derived fields with __post_init__

  • create immutable records with frozen=True

  • build simple data class hierarchies

  • serialize data class instances with dataclasses.asdict() for logging and APIs

The Problem with Manual Classes#

A correct, type-annotated Stock class needs at minimum __init__, __repr__, and __eq__. Here is what that looks like written by hand — this is the code @dataclass replaces.

 1class Stock:
 2    def __init__(self, ticker: str, price: float, shares: int) -> None:
 3        self.ticker = ticker
 4        self.price = price
 5        self.shares = shares
 6
 7    def __repr__(self) -> str:
 8        return f"Stock(ticker={self.ticker!r}, price={self.price}, shares={self.shares})"
 9
10    def __eq__(self, other: object) -> bool:
11        if not isinstance(other, Stock):
12            return NotImplemented
13        return (self.ticker, self.price, self.shares) == (
14            other.ticker, other.price, other.shares
15        )
16
17s1 = Stock("AAPL", 189.30, 100)
18s2 = Stock("AAPL", 189.30, 100)
19print(s1)
20print(s1 == s2)
Stock(ticker='AAPL', price=189.3, shares=100)
True

And now as a dataclass:

 1from dataclasses import dataclass
 2
 3@dataclass
 4class Stock:
 5    ticker: str
 6    price: float
 7    shares: int
 8
 9s1 = Stock("AAPL", 189.30, 100)
10s2 = Stock("AAPL", 189.30, 100)
11print(s1)         # __repr__ auto-generated
12print(s1 == s2)   # __eq__ auto-generated
Stock(ticker='AAPL', price=189.3, shares=100)
True

@dataclass inspects the type-annotated class variables and generates __init__, __repr__, and __eq__ at class-definition time. The result is identical in behavior to the 18-line manual version above. You can still add your own methods, properties, and class-level logic — a data class is a regular Python class.

Defaults and the Mutable Default Trap#

Fields with no default are required arguments. Fields with a default are optional — but there is one rule you must follow: never use a mutable object (list, dict, set) as a direct default. Python shares that object across all instances, which causes subtle bugs. (This same issue also exists if you use a list as a default parameter for a function.)

 1from dataclasses import dataclass, field
 2from datetime import datetime
 3
 4@dataclass
 5class Order:
 6    order_id: int
 7    ticker: str
 8    quantity: int
 9    price: float
10    side: str = "BUY"                                    # scalar default — fine
11    timestamp: datetime = field(default_factory=datetime.now)  # factory — fine
12
13o = Order(1001, "MSFT", 50, 415.20)
14print(o)
Order(order_id=1001, ticker='MSFT', quantity=50, price=415.2, side='BUY', timestamp=datetime.datetime(2026, 6, 20, 15, 2, 19, 522857))
 1from dataclasses import dataclass, field
 2
 3# Wrong: all Portfolio instances would share the same list
 4# @dataclass
 5# class Portfolio:
 6#     name: str
 7#     holdings: list = []   # raises ValueError at class-definition time
 8
 9# Correct: field(default_factory=list) creates a fresh list per instance
10@dataclass
11class Portfolio:
12    name: str
13    holdings: list[str] = field(default_factory=list)
14
15p1 = Portfolio("Growth")
16p2 = Portfolio("Income")
17
18p1.holdings.append("AAPL")
19p2.holdings.append("MSFT")
20
21print(p1)   # holdings=['AAPL'] — independent list
22print(p2)   # holdings=['MSFT'] — independent list
Portfolio(name='Growth', holdings=['AAPL'])
Portfolio(name='Income', holdings=['MSFT'])

The same rule applies to datetime.now: pass the callable, not the result. field(default_factory=datetime.now) calls datetime.now() fresh for each instance. Writing timestamp: datetime = datetime.now() evaluates it once at class-definition time and freezes that value forever.

Validating Inputs with __post_init__#

__post_init__ is called by the generated __init__ immediately after all fields are set. Use it to enforce invariants, normalise data, or compute derived fields that depend on other fields.

 1from dataclasses import dataclass, field
 2
 3@dataclass
 4class Position:
 5    ticker: str
 6    shares: int
 7    price: float
 8    total_value: float = field(init=False)   # derived — not an __init__ parameter
 9
10    def __post_init__(self) -> None:
11        self.ticker = self.ticker.upper()    # normalise to uppercase
12        if self.shares <= 0:
13            raise ValueError(f"shares must be positive, got {self.shares}")
14        if self.price <= 0:
15            raise ValueError(f"price must be positive, got {self.price}")
16        self.total_value = self.shares * self.price
17
18p = Position("tsla", 25, 242.50)
19print(p)
20print(f"Total value: ${p.total_value:,.2f}")
Position(ticker='TSLA', shares=25, price=242.5, total_value=6062.5)
Total value: $6,062.50
 1# Validation fires at construction time — bad data never enters the system
 2try:
 3    bad = Position("AAPL", -10, 189.30)
 4except ValueError as e:
 5    print(f"Caught: {e}")
 6
 7# Sorting a portfolio by total value using a key function
 8portfolio = [
 9    Position("AAPL",  100, 189.30),
10    Position("TSLA",   25, 242.50),
11    Position("MSFT",   50, 415.20),
12    Position("GOOG",   10, 175.80),
13]
14
15for pos in sorted(portfolio, key=lambda p: p.total_value, reverse=True):
16    print(f"  {pos.ticker:4s}  {pos.shares:>4} shares  ${pos.total_value:>10,.2f}")
Caught: shares must be positive, got -10
  MSFT    50 shares  $ 20,760.00
  AAPL   100 shares  $ 18,930.00
  TSLA    25 shares  $  6,062.50
  GOOG    10 shares  $  1,758.00

Immutable Records with frozen=True#

Some domain objects should never change after they are created — a settled transaction, an audit log entry, a confirmed order fill. Pass frozen=True to make all fields read-only. Any attempt to mutate a field raises FrozenInstanceError.

A bonus: frozen instances are hashable, so they can be stored in a set or used as dict keys.

 1from dataclasses import dataclass, field
 2from datetime import datetime
 3
 4@dataclass(frozen=True)
 5class Transaction:
 6    transaction_id: str
 7    amount: float
 8    description: str
 9    timestamp: datetime = field(default_factory=datetime.now)
10
11t = Transaction("TXN-001", 1_500.00, "Wire transfer — AAPL settlement")
12print(t)
13
14# Mutation is blocked
15try:
16    t.amount = 999.00
17except Exception as e:
18    print(f"{type(e).__name__}: {e}")
19
20# Frozen instances are hashable — useful for deduplication
21ledger: set[Transaction] = {t}
22print(f"In ledger: {t in ledger}")
Transaction(transaction_id='TXN-001', amount=1500.0, description='Wire transfer — AAPL settlement', timestamp=datetime.datetime(2026, 6, 20, 15, 2, 19, 541397))
FrozenInstanceError: cannot assign to field 'amount'
In ledger: True

Derived fields in a frozen dataclass#

__post_init__ still works with frozen=True, but you cannot write self.field = value — the frozen guard blocks it. Use object.__setattr__(self, 'field', value) instead. Limit this to __post_init__ only.

 1from dataclasses import dataclass, field
 2
 3@dataclass(frozen=True)
 4class Transaction:
 5    transaction_id: str
 6    amount: float
 7    description: str
 8    amount_formatted: str = field(init=False)
 9
10    def __post_init__(self) -> None:
11        # Normal assignment blocked; use object.__setattr__ in __post_init__ only
12        object.__setattr__(self, "amount_formatted", f"${self.amount:,.2f}")
13
14t = Transaction("TXN-002", 4_250.75, "Quarterly dividend reinvestment")
15print(t)
16print(t.amount_formatted)
Transaction(transaction_id='TXN-002', amount=4250.75, description='Quarterly dividend reinvestment', amount_formatted='$4,250.75')
$4,250.75

Inheritance#

Data classes support inheritance the same way regular classes do, with one rule to know: parent fields come before child fields in the generated __init__, regardless of how they appear in the source.

 1from dataclasses import dataclass
 2
 3@dataclass
 4class BaseOrder:
 5    order_id: int
 6    ticker: str
 7    quantity: int
 8    side: str
 9
10@dataclass
11class LimitOrder(BaseOrder):
12    limit_price: float
13    time_in_force: str = "DAY"
14
15@dataclass
16class MarketOrder(BaseOrder):
17    slippage_tolerance: float = 0.01
18
19# Parent fields come first in __init__
20lo = LimitOrder(1001, "AAPL", 100, "BUY", 189.50)
21mo = MarketOrder(1002, "MSFT",  50, "SELL")
22
23print(lo)
24print(mo)
25print(isinstance(lo, BaseOrder))
LimitOrder(order_id=1001, ticker='AAPL', quantity=100, side='BUY', limit_price=189.5, time_in_force='DAY')
MarketOrder(order_id=1002, ticker='MSFT', quantity=50, side='SELL', slippage_tolerance=0.01)
True

One constraint: if a parent data class has any field with a default, all fields in every subclass must also have defaults. This mirrors the rule that optional parameters cannot precede required ones in __init__.

Putting It All Together: Structured Event Logging#

In the Logging Notebook we used logger.info(msg, extra=context_dict) to attach structured data to log records. Data classes pair naturally with this pattern: dataclasses.asdict() converts any instance to a plain dict in one call, and json.dumps(..., default=str) serialises the result — including datetime fields — to JSON.

 1import json
 2import logging
 3import sys
 4from dataclasses import dataclass, field, asdict
 5from datetime import datetime
 6
 7logging.basicConfig(
 8    level=logging.INFO,
 9    format="%(asctime)s %(levelname)-8s %(message)s",
10    datefmt="%H:%M:%S",
11    stream=sys.stdout,
12    force=True,
13)
14
15@dataclass(frozen=True)
16class TradeEvent:
17    event_id: str
18    ticker: str
19    side: str
20    quantity: int
21    price: float
22    timestamp: datetime = field(default_factory=datetime.now)
23
24logger = logging.getLogger("trading.events")
25
26for evt in [
27    TradeEvent("EVT-001", "AAPL", "BUY",  100, 189.30),
28    TradeEvent("EVT-002", "MSFT", "SELL",  50, 415.20),
29    TradeEvent("EVT-003", "TSLA", "BUY",   25, 242.50),
30]:
31    # asdict() converts the dataclass to a dict; extra= attaches it to the log record
32    logger.info("Trade executed: %s %s %d @ $%.2f",
33                evt.side, evt.ticker, evt.quantity, evt.price,
34                extra=asdict(evt))
15:02:19 INFO     Trade executed: BUY AAPL 100 @ $189.30
15:02:19 INFO     Trade executed: SELL MSFT 50 @ $415.20
15:02:19 INFO     Trade executed: BUY TSLA 25 @ $242.50
1# For JSON log aggregation — one JSON object per line, datetime serialised as string
2print("=== Structured JSON output ===")
3for evt in [
4    TradeEvent("EVT-001", "AAPL", "BUY",  100, 189.30),
5    TradeEvent("EVT-002", "MSFT", "SELL",  50, 415.20),
6]:
7    print(json.dumps(asdict(evt), default=str))
=== Structured JSON output ===
{"event_id": "EVT-001", "ticker": "AAPL", "side": "BUY", "quantity": 100, "price": 189.3, "timestamp": "2026-06-20 15:02:19.557718"}
{"event_id": "EVT-002", "ticker": "MSFT", "side": "SELL", "quantity": 50, "price": 415.2, "timestamp": "2026-06-20 15:02:19.557719"}

Best Practices#

  • Use @dataclass for value objects — classes whose purpose is to hold data. If the class has significant logic and behaviour, a regular class may communicate intent better.

  • Use frozen=True for records that should not change — transactions, confirmed fills, audit entries. Immutability prevents entire classes of bugs.

  • Always use field(default_factory=...) for mutable defaults — never holdings: list = []. This is the most common mistake and the only one that surfaces as a ValueError at class-definition time.

  • Put validation in __post_init__ and raise early — an invalid object that propagates silently is far harder to debug than one that refuses to be constructed.

  • Use field(init=False) for derived fields — keeps the constructor signature clean and prevents callers from passing stale pre-computed values.

  • Use dataclasses.replace(obj, field=new_value) to update frozen instances — it creates a copy with the changed field and re-runs __post_init__.

Suggested LLM Prompts#

  • Explain when to choose @dataclass vs typing.NamedTuple vs a plain dict for modelling a FinTech domain object.

  • What are the tradeoffs between frozen=True and using @property with no setter to make fields read-only?

  • How does __post_init__ interact with inheritance? If both parent and child define __post_init__, what happens and how do you call both?

  • What are the limitations of dataclasses.asdict() when fields contain custom objects, datetime, or Decimal?

  • Show how to add custom __str__ formatting to a data class without losing the auto-generated __repr__.

  • How would you implement a data class field that is expensive to compute and should be calculated lazily only on first access?

Review Questions#

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

  2. Why does holdings: list = [] raise a ValueError, and what is the correct syntax?

  3. When does __post_init__ run, and what are its two most common uses?

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

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

  6. In a data class hierarchy, in what order do parent and child fields appear in __init__?

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

  8. What is dataclasses.replace() used for?

Answers

Drill#

Create a file positions.py and build a small position-tracking module step by step:

  1. Define a frozen=True Symbol dataclass with a single ticker: str field. In __post_init__, use object.__setattr__ to uppercase the ticker.

  2. Define a Position dataclass with symbol: Symbol, shares: int, cost_basis: float, and a derived total_cost: float computed in __post_init__. Add validation: shares > 0 and cost_basis > 0.

  3. Create three positions (AAPL, MSFT, TSLA) and print them sorted by total_cost descending.

  4. Use dataclasses.replace() on one position to increase the share count. Print the old and new total_cost values and confirm __post_init__ re-ran.

  5. Use dataclasses.asdict() and json.dumps(..., default=str) to print each position as a line of JSON.

Drill answers

Exercises#

Exercise 1 — Convert a manual class (Beginner)

Convert the following class to a @dataclass:

class BankAccount:
    _count: int = 0

    def __init__(self, account_id: str, holder: str, balance: float = 0.0) -> None:
        BankAccount._count += 1
        self.account_id = account_id
        self.holder = holder
        self.balance = balance

    def __repr__(self) -> str:
        return f"BankAccount({self.account_id!r}, {self.holder!r}, balance={self.balance})"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, BankAccount):
            return NotImplemented
        return self.account_id == other.account_id

Preserve all behaviour: balance defaults to 0.0, _count tracks total accounts created, and equality is based solely on account_id.


Exercise 2 — Validation and derived fields (Intermediate)

Build an OptionContract frozen data class with fields ticker: str, strike: float, expiry: datetime.date, option_type: str, and premium: float. In __post_init__:

  • Normalise option_type to uppercase; validate it is "CALL" or "PUT".

  • Validate strike > 0 and premium >= 0.

Add an instance method is_in_the_money(spot_price: float) -> bool that returns True if the option has intrinsic value (CALL: spot > strike; PUT: spot < strike).


Exercise 3 — Hierarchy and logging (Intermediate)

Build a BaseReport data class (report_id: str, portfolio_value: float) and two subclasses:

  • VaRReport adds var_95: float. In __post_init__, set a derived risk_level: str to "HIGH" if var_95 / portfolio_value > 0.05, "MEDIUM" if > 0.02, else "LOW".

  • StressReport adds scenario: str and loss_amount: float. Set risk_level by the same proportional thresholds.

Instantiate one of each, log them as structured JSON using asdict(), and confirm the risk_level is computed correctly.

Exercise answers