Immutability
medium 45 minAn immutable object keeps the value it was born with.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Objects at run time: which object is touched, which is new, and who still sees the old one.
Operations
A change makes a new object
100 dollars minus 25, without touching the wallet.
Step 1 of 5
Create
The wallet gets 100 USD. Its value is fixed for life.
Step 1: Create
wallet = Money(10000, "USD")tip = Money(-2500, "USD")after = wallet.plus(tip)def plus(self, other): if self.currency != other.currency: raise ValueError return Money(self.cents + other.cents, self.currency)- Good for
- Every small value
- Costs
- One more small object
The caller decides which name points at which object. The objects stay.
In the real world
The same immutability doing real jobs. Pick one and step through it.
The immutable object everybody uses. Why a lonely upper() does nothing.
Step 1 of 4
A string
| name points at | other strings | |
|---|---|---|
| name = "Ada" | "Ada" | none |
| name.upper() | ||
| x = name.upper() | ||
| name = x |
The name points at the string Ada.
Step 1: A string
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Frozen class, open list
criticalThe field is fixed, the list is not.
Wrong@dataclass(frozen=True)class Team: names: listRightnames: tupledef __post_init__(self): object.__setattr__(self, "names", tuple(self.names))The result is ignored
majorImmutable objects answer, they do not change.
Wrongprice.plus(tax)Rightprice = price.plus(tax)Check, then copy
criticalBetween the two lines another thread can change the argument.
Wrongcheck(dates)self.dates = tuple(dates)Rightself.dates = tuple(dates)check(self.dates)Append on copies in a loop
majorAbout n x n / 2 copied slots.
Wrongfor line in source: receipt = add_line(receipt, line)Rightreceipt = Receipt(tuple(source), now)Two references for one truth
criticalA reader can meet the new limit with the old burst.
Wrongstore.limit = 90store.burst = 120Rightstore.update(lambda s: replace(s, limit=90, burst=120))
Interview tips
Say deep
- Name each field's type
- Say who else holds it
- Copy in the constructor
Value or entity
- Money and dates are frozen
- Accounts change in one place
- Say why
Threads
- Snapshot and one reference
- Lost update: compare and set
- Stale reads are a choice
Cost
- Small: just copy
- Loop: builder
- Large: share the structure