Object-oriented programming · lesson 4 of 17
Parts in this lesson
Araise ValueError(...)2.6: refuse to make a bad object
Breturn tuple(self._loans)hand out a copy, not your own list
C@dataclass(frozen=True)can't change after it's made
D__slots__no new attributes

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 raising ValueError
  • 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:

Step 1 code main.py
Edit the code, then run it again

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.

Step 2 code main.py
Edit the code, then run it again

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.

The class in the code below
Book
  • +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.
Step 3 code main.py
Edit the code, then run it again
  • __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.

Step 4 code main.py
Edit the code, then run it again

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.

Step 4 code main.py
Edit the code, then run it again

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.

Step 5 code main.py
Edit the code, then run it again
  • Line 13 tries to change the year, and the dataclass raises FrozenInstanceError, a kind of AttributeError.
  • 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() from dataclasses (line 24) copies a book with some fields changed. Line 26 shows the first dune is 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.

Step 6 code main.py
Edit the code, then run it again

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.

Five ways to keep an object valid
ToolWhat it stops
Check in __init__A bad object is never made
Change data only in methodsEvery change is checked
Return a tuple or a copyOutside code can’t change the object’s lists
frozen=TrueNothing 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.

Keeping objects valid in three languages
PythonJavaRust
Refusing a bad objectraise ValueError in __init__throw an exception in the constructornew returns a Result, an Err for bad values
Handing out a listA tuple or a copyList.copyOf or an unmodifiable viewA borrowed slice, &[Loan], which can’t be changed
Can’t change after it’s made@dataclass(frozen=True)final fields, or a recordThe default: changing needs mut
New attributes at run timeAllowed, unless the class has __slots__Never: fields are fixed by the classNever: 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.

What does this program print?
from dataclasses import dataclass


@dataclass(frozen=True)
class Book:
    title: str
    year: int


shelf = {Book("Dune", 1965), Book("Emma", 1815), Book("Dune", 1965)}
print(len(shelf))
A Member keeps its loans in self._loans. What should get_loans() return?
Book("", -2) should never make a book. Where does the check go?

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.

All sources for Simple Python