Keeping objects valid
Last updated
A book with no title and minus two copies is nonsense, but nothing so far stops you making one. In this lesson you'll write down the rules an object must always keep, refuse to make an object that breaks them, let only the object's own methods change it, and stop it handing out a list that other code can change behind its back. Then you'll make objects that can't change at all with frozen=True, and stop new attributes appearing with __slots__.
By the end of this lesson you can
- Say what an invariant is, and check one in
__init__by raisingValueError - Keep an object valid by changing its data only through its own methods
- Return a tuple or a copy instead of an object's own list
- Make objects that can't change with
@dataclass(frozen=True), and stop new attributes with__slots__
Invariants: rules that are always true
An invariant is a rule about an object that must be true the whole time it exists. For a book in this library:
- It has a title, which isn't empty.
- It has at least one copy, and the copies on the shelf are never fewer than 0 or more than it has.
For a member: they never have more loans than their limit of 3.
Every method can count on the invariants being true when it starts, as long as every method leaves them true when it ends. That's what makes the rules work. Here's what happens when an object breaks them from the start:
Line 12 makes a book with no title and -2 copies, and nothing complains. lend() checks for 0 copies, so it was written trusting that copies are never negative. On line 13 it lends a copy that doesn't exist, and line 14 shows -3. The rule in lend() was right; the object was wrong from the moment it was made.
Checking in __init__
__init__ is the first place to keep the invariants. If a value breaks a rule, raise a ValueError (lesson 2.6) instead of making the object.
Lines 3 to 6 check the title and the number of copies before anything is stored. When one raises, the object is never finished: Book(title, copies) on line 13 doesn't give back anything, so book is never set to a bad book, and line 16 says why.
ValueError is the usual error for this: the value is the right kind, a number, but not one that makes sense. The message says what was wrong and what it was.
Methods as the only way to change it
Checking once isn't enough. The object has to stay valid as it changes. So, as in lessons 4.2 and 4.3, keep the data in _names and change it only in the object's own methods, each of which keeps the invariants.
- +title: str
- #_total: int
- #_in: int
- +__init__(title: str, copies: int)
- +get_copies(): int
- +lend()
- +give_back()
- Class Book; attributes: title, _total, _in; methods: __init__, get_copies, lend, give_back.
__init__(line 3) refuses a book with no copies.lend()(line 12) never takes the copies on the shelf below 0.give_back()(line 17) never takes them above the total. Line 28 tries to give back a copy that was never lent, and is refused.get_copies()(line 9) is a getter with no setter, so nothing outside can set the count.
There's no set_copies(). A setter that accepts any number between 0 and the total would still let outside code invent loans. Methods named for what happens in the library, lend() and give_back(), keep the count true to what really happened.
Don't hand out your insides
A member's loans are kept in a list, _loans, and borrow() checks the limit of 3. Other code needs to see the loans, so the member has a getter. Here someone uses what the getter gives back. Run it.
A copy works, but the caller can still append to it and think it changed something. A tuple is better: it can't be changed at all, so the mistake shows up straight away.
Line 8 builds a new tuple from the list each time. Line 21 tries to append to it, and Python raises an AttributeError: tuples have no append. Reading still works as before: line 24 loops over the loans.
The rule: a method should never give back a list, dict or set that the object keeps for itself. Give back a tuple or a copy.
Objects that can't change: frozen=True
Some objects should never change once they're made: a book's title, author and year are fixed facts. @dataclass(frozen=True) makes a dataclass whose fields can't be set after __init__. An object that can't be changed is called immutable, like a tuple or a string.
- Line 13 tries to change the year, and the dataclass raises
FrozenInstanceError, a kind ofAttributeError. - Lesson 3.6 said a dataclass has no hash, so its objects can't go in a set. Frozen ones do: their fields can't change, so their hash can't either. Line 21 puts three books in a set and the duplicate Dune goes. Line 23 uses a book as a dict key.
- To "change" a frozen object, make a new one.
replace()fromdataclasses(line 24) copies a book with some fields changed. Line 26 shows the firstduneis untouched.
An immutable object only needs checking once, when it's made. After that its invariants can't break, because nothing can change.
__slots__: no new attributes
Python lets any line of a program add a new attribute to an object. Usually that's a typo waiting to happen: sam.limt = 6 makes a new attribute called limt, and limit stays as it was, with no error.
__slots__, a tuple of names in the class body, lists every attribute an object of the class may have. Setting any other name raises an AttributeError.
Line 11 sets limit, which is in the slots. Line 14 misspells it, and Python refuses: the object has no attribute limt, and no __dict__ (the dict that vars() shows) to put new ones in. Line 17 shows limit is still 5.
Delete line 2 and run it again: the typo goes through without a word, and the program prints 5 twice, with a limt of 6 hidden in the object. Objects with slots also use less memory, which matters when there are millions of them.
| Tool | What it stops |
|---|---|
Check in __init__ | A bad object is never made |
| Change data only in methods | Every change is checked |
| Return a tuple or a copy | Outside code can’t change the object’s lists |
frozen=True | Nothing can change after it’s made |
__slots__ | No attributes appear by accident |
In other languages
This step is optional. It's for anyone who will meet Java, C# or Rust later.
| Python | Java | Rust | |
|---|---|---|---|
| Refusing a bad object | raise ValueError in __init__ | throw an exception in the constructor | new returns a Result, an Err for bad values |
| Handing out a list | A tuple or a copy | List.copyOf or an unmodifiable view | A borrowed slice, &[Loan], which can’t be changed |
| Can’t change after it’s made | @dataclass(frozen=True) | final fields, or a record | The default: changing needs mut |
| New attributes at run time | Allowed, unless the class has __slots__ | Never: fields are fixed by the class | Never: fields are fixed by the struct |
C# works like Java here, with readonly fields and records. In Java, C# and Rust every class or struct already behaves as if it had __slots__: its fields are fixed when it's written. Rust also makes everything immutable unless you write mut, the opposite of Python's default. Simple Rust 4.2 keeps a value valid with a private field and checked methods.
Check what you learned
Three questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Built-in Exceptions: ValueError: the error for a value of the right type that doesn't make sense
- dataclasses: Frozen instances
- dataclasses.replace: a new object with some fields changed
- The Python Language Reference: __slots__
- Glossary: immutable
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Tutorials: A Strategy for Defining Immutable Objects: final fields and copies in Java
- The Rust Programming Language: Variables and Mutability: values that can’t change unless marked mut in Rust