When a script starts passing around dicts with the same six keys, it is time for a class: a type that bundles data with the functions that work on it. Modern Python makes simple classes almost free with dataclasses, and makes swappable parts easy with protocols (duck typing that a type checker understands). This lesson models servers for an inventory tool, from a plain class to frozen dataclasses with validation, and shows the two class bugs that surprise everyone once: a list defined on the class instead of the instance, and objects that cannot go into a set.
Difficulty: Intermediate · Know this first: Lesson 35, Lesson 31
This bar adds up developer minutes to model the data and trust it. It is a worked example, not a measurement. The __init__ and hashing hops hold the surprises.
Create servers and tag one of them. Choose where the tags list is created.
Shared: one list on the class, so every server shows the tag
Three questions. No score is saved anywhere — this is just you against the material.
Object-oriented Python grows in four levels: classes and instances, dataclasses, design with composition and protocols, and the data model underneath.
At the basic level you can write and use a class.
class Name:, __init__(self, ...), self.attr = value.self; calling obj.method().__repr__ for readable output.Where it breaks: forgetting self as the first parameter, so Python passes the object into the first argument you meant for data.
Try it: Basic
def is_prod(): return self.env == "prod" inside a class. Calling s.is_prod() fails. Why?
Now do it: Write a class with one attribute and one method, and print an instance.
At the intermediate level data classes are one decorator.
@dataclass with typed fields and defaults; field(default_factory=list).frozen=True, order=True, slots=True; asdict() and replace().__post_init__ for validation and conversion.Try it: Intermediate
How do you get a modified copy of a frozen dataclass?
Now do it: Make a frozen dataclass and use replace() on it.
At the advanced level classes are designed for change.
super() when inheriting.typing.Protocol for interfaces; abstract base classes (abc.ABC) when you want enforcement at runtime.Try it: Advanced
What is the difference between a Protocol and an abstract base class?
Now do it: Define a Notifier protocol and two unrelated classes that satisfy it.
At the master level you shape how objects behave in the language.
__eq__ and __hash__ contract; functools.total_ordering; __slots__ for memory.__enter__/__exit__), iterators, and descriptors.Trade-off: rich classes centralise rules and add indirection; plain functions on dicts are quick to write and push validation onto every caller.
Try it: Master
Two equal objects must have what property if they are used in sets?
Now do it: Write a class with __eq__ only and check hash() on it.
The inventory model as frozen dataclasses with validation and a protocol, using only the standard library.
from dataclasses import dataclass, field, replace
from typing import Protocol
ENVS = {"dev", "staging", "prod"}
@dataclass(frozen=True, order=True)
class Server:
name: str
env: str
cpus: int = 2
tags: tuple = () # immutable, so the object can be hashed
def __post_init__(self):
if self.env not in ENVS:
raise ValueError(f"{self.name}: unknown env {self.env!r}")
object.__setattr__(self, "cpus", int(self.cpus)) # convert inside a frozen class
if self.cpus < 1:
raise ValueError(f"{self.name}: cpus must be positive")
@property
def is_prod(self):
return self.env == "prod"
class Notifier(Protocol):
def send(self, message: str) -> None: ...
@dataclass
class Fleet:
notifier: Notifier
servers: set = field(default_factory=set)
def add(self, server):
self.servers.add(server) # duplicates are dropped
def report(self):
prod = sorted(s for s in self.servers if s.is_prod)
self.notifier.send(f"{len(prod)} prod servers: {', '.join(s.name for s in prod)}")
class PrintNotifier:
def send(self, message):
print(message)
fleet = Fleet(PrintNotifier())
for row in [("web1", "prod", "4"), ("web1", "prod", "4"), ("db1", "prod", 8), ("ci1", "dev", 2)]:
fleet.add(Server(*row))
fleet.report()
print(replace(Server("web2", "staging"), env="prod"))
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A compliance report flagged every server at once.
Models are dataclasses (which reject mutable defaults), frozen where possible, and a test creates two instances and checks that changing one does not change the other.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Type each one, read what it prints, and compare it with the note above it.
A class attribute is shared; an instance attribute is not.
python3 -c "class S:
tags = []
a, b = S(), S(); a.tags.append('pci'); print(b.tags, a.tags is b.tags)"Dataclasses refuse a mutable default.
python3 -c "from dataclasses import dataclass
@dataclass
class S:
tags: list = []" 2>&1 | tail -1A frozen dataclass is hashable; a normal one is not.
python3 -c "from dataclasses import dataclass
@dataclass
class A:
n: str
@dataclass(frozen=True)
class B:
n: str
print(len({B('x'), B('x')}))
print(A.__hash__)"Inspect what @dataclass generated.
python3 -c "from dataclasses import dataclass, fields
@dataclass(order=True)
class S:
name: str
cpus: int = 2
print([f.name for f in fields(S)], sorted([S('b'), S('a', 8)]))"inventory_model.pyThis program loads two overlapping inventory exports into frozen dataclasses with validation, removes duplicates with a set, and rejects bad rows with clear messages. Save it as inventory_model.py, then run it.
# inventory_model.py
from dataclasses import dataclass
ENVS = {"dev", "staging", "prod"}
@dataclass(frozen=True, order=True)
class Server:
name: str
env: str
cpus: int
def __post_init__(self):
if self.env not in ENVS:
raise ValueError(f"{self.name}: unknown env {self.env!r}")
object.__setattr__(self, "cpus", int(self.cpus))
export_a = [("web1", "prod", "4"), ("db1", "prod", "8"), ("ci1", "dev", "2")]
export_b = [("web1", "prod", 4), ("web2", "prdo", 4), ("db1", "prod", 8), ("cache1", "staging", 2)]
servers, rejected = set(), []
for row in export_a + export_b:
try:
servers.add(Server(*row))
except ValueError as e:
rejected.append(str(e))
print(f"{len(export_a) + len(export_b)} rows -> {len(servers)} unique servers")
for s in sorted(servers):
print(" ", s)
print("rejected:", rejected)
Run it, and you should see this output:
$ python3 inventory_model.py 7 rows -> 4 unique servers Server(name='cache1', env='staging', cpus=2) Server(name='ci1', env='dev', cpus=2) Server(name='db1', env='prod', cpus=8) Server(name='web1', env='prod', cpus=4) rejected: ["web2: unknown env 'prdo'"]
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-classes-dataclasses-and-protocols && cd ~/labs/python-classes-dataclasses-and-protocols) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Python Classes, Dataclasses, and Protocols", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'A class attribute is shared; an instance attribute is not.'
'Dataclasses refuse a mutable default.'
'A frozen dataclass is hashable; a normal one is not.'
'Inspect what @dataclass generated.'
)
step_1() {
python3 -c "class S:
tags = []
a, b = S(), S(); a.tags.append('pci'); print(b.tags, a.tags is b.tags)"
}
step_2() {
python3 -c "from dataclasses import dataclass
@dataclass
class S:
tags: list = []" 2>&1 | tail -1
}
step_3() {
python3 -c "from dataclasses import dataclass
@dataclass
class A:
n: str
@dataclass(frozen=True)
class B:
n: str
print(len({B('x'), B('x')}))
print(A.__hash__)"
}
step_4() {
python3 -c "from dataclasses import dataclass, fields
@dataclass(order=True)
class S:
name: str
cpus: int = 2
print([f.name for f in fields(S)], sorted([S('b'), S('a', 8)]))"
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
tail, Pipes, Redirection.Model a fleet inventory with servers, their disks, and their owners, loaded from two CSV exports that overlap.
Which objects are frozen and which change? Where is input validated? How are duplicates across the two exports removed? How does the report send its output in production and in tests?
Say 1,200 servers in each export with 300 in both, three disks per server, and 40 owning teams.
Frozen dataclasses for Server and Disk with __post_init__ validation; a classmethod from_row for each export; a set to deduplicate; a Fleet holding servers and a Notifier protocol; a fake notifier in tests; asdict() for JSON output.
Frozen objects make deduplication and sharing safe, and every change means building a new object with replace(). Strict validation rejects bad rows loudly; decide whether one bad row should stop the whole import or be reported and skipped.