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
@dataclassdefine fields with type annotations and sensible defaults
validate inputs and compute derived fields with
__post_init__create immutable records with
frozen=Truebuild 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
@dataclassfor 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=Truefor records that should not change — transactions, confirmed fills, audit entries. Immutability prevents entire classes of bugs.Always use
field(default_factory=...)for mutable defaults — neverholdings: list = []. This is the most common mistake and the only one that surfaces as aValueErrorat 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
@dataclassvstyping.NamedTuplevs a plaindictfor modelling a FinTech domain object.What are the tradeoffs between
frozen=Trueand using@propertywith 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, orDecimal?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#
What three methods does
@dataclassgenerate by default?Why does
holdings: list = []raise aValueError, and what is the correct syntax?When does
__post_init__run, and what are its two most common uses?What does
frozen=Trueprevent, and what extra capability does it add?Why must you use
object.__setattr__()inside__post_init__of a frozen data class?In a data class hierarchy, in what order do parent and child fields appear in
__init__?What does
dataclasses.asdict()return, and why is it useful with the loggingextra=parameter?What is
dataclasses.replace()used for?
Drill#
Create a file positions.py and build a small position-tracking module step by step:
Define a
frozen=TrueSymboldataclass with a singleticker: strfield. In__post_init__, useobject.__setattr__to uppercase the ticker.Define a
Positiondataclass withsymbol: Symbol,shares: int,cost_basis: float, and a derivedtotal_cost: floatcomputed in__post_init__. Add validation:shares > 0andcost_basis > 0.Create three positions (
AAPL,MSFT,TSLA) and print them sorted bytotal_costdescending.Use
dataclasses.replace()on one position to increase the share count. Print the old and newtotal_costvalues and confirm__post_init__re-ran.Use
dataclasses.asdict()andjson.dumps(..., default=str)to print each position as a line of JSON.
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_typeto uppercase; validate it is"CALL"or"PUT".Validate
strike > 0andpremium >= 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:
VaRReportaddsvar_95: float. In__post_init__, set a derivedrisk_level: strto"HIGH"ifvar_95 / portfolio_value > 0.05,"MEDIUM"if> 0.02, else"LOW".StressReportaddsscenario: strandloss_amount: float. Setrisk_levelby the same proportional thresholds.
Instantiate one of each, log them as structured JSON using asdict(), and confirm the risk_level is computed correctly.