The service this track builds
Every chapter in this track works on one small program: the ticketing service of an invented company. Marigold Hardware runs three shops, and anything that breaks in a shop (a till that will not print, a cold room alarm, a staff login that stopped working) becomes a ticket in a service the staff call Tally. A requester opens a ticket, an agent picks it up, the ticket moves from open to in progress to resolved to closed, and comments collect along the way. That is the whole product. It is small enough to hold in your head and real enough that every idea in this track has a job to do in it.
The examples are Python, run on Python 3.13, and the ideas carry to TypeScript, Go, Java or C#; where the syntax differs in a way that matters, the chapter says so. This first chapter builds the ticket itself as a Python object, in memory, with no web framework and no database. Chapters 04 and 05 move it into Django, chapters 06 and 07 put a login in front of it, chapter 08 tests it, chapters 09 and 10 return to the login with the other grants and with OpenID Connect, and chapter 11 adds apps, the admin and signals.
Start with what Tally has to remember about one ticket: an id, a title, a longer body, a priority, a status, who asked, who is working on it, and when it was opened. Three of those are not free text. Priority is one of low, normal or high. Status is one of open, in progress, resolved or closed. The id is assigned by the service, never typed by a person. The rest of this chapter is about putting those facts into a Python class so that the program, not a comment, enforces them.
Classes, instances and the self that is not special
A class is a factory for objects that share behaviour. The first version of a ticket is five lines:
class Ticket:
SERVICE = "tally" # a class attribute: one value, shared by every Ticket
def __init__(self, title, priority="normal"):
self.title = title # instance attributes: one set per ticket
self.priority = priority
self.status = "open"
t = Ticket("Till 2 will not print receipts", priority="high")
print(t.title, t.priority, t.status) # Till 2 will not print receipts high open
print(t.SERVICE, Ticket.SERVICE) # tally tally
SERVICE lives on the class and is found through any instance. title, priority and status live on the instance, set inside __init__, and each ticket gets its own. That split is the first thing to be deliberate about, because getting it wrong produces a bug that looks impossible.
self is not a keyword. When you write t.describe(), Python runs Ticket.describe(t), and whatever the first parameter of describe is called receives t. You could name it this. Nobody does, because every Python reader expects self, but knowing that it is an ordinary parameter explains two things: why forgetting it produces the error "takes 0 positional arguments but 1 was given", and why a method can be called on the class with an explicit instance, which test code sometimes does.
Here is the bug that the class-versus-instance split sets up. A ticket needs a list of tags, and the obvious place to put an empty list is on the class:
class Ticket:
tags = [] # one list, created once, shared by every ticket
def __init__(self, title):
self.title = title
def tag(self, label):
self.tags.append(label) # finds the class's list, since the instance has none
till = Ticket("Till 2 will not print receipts")
alarm = Ticket("Cold room alarm sounding")
till.tag("hardware")
print(alarm.tags) # ['hardware']
print(till.tags is alarm.tags) # True
The cold room alarm now carries a tag nobody gave it. tags = [] ran once, when the class body ran, so there is exactly one list, and self.tags.append finds it through the class because the instance has no attribute of its own called tags. The same evaluated-once rule makes a mutable default argument dangerous, and the fix is the same: create the list per instance, inside __init__.
class Ticket:
def __init__(self, title):
self.title = title
self.tags = [] # a fresh list for each ticket
till = Ticket("Till 2 will not print receipts")
alarm = Ticket("Cold room alarm sounding")
till.tags.append("hardware")
print(alarm.tags) # []
The rule to carry: a class attribute is for a value every instance should share and nobody should mutate, such as a name or a limit. Anything that one ticket changes belongs on self.
By default each instance carries a dictionary of its attributes, which is why t.anything = value always works even when the class author never mentioned anything. For a few thousand tickets that is fine. For a class created a million times, such as one line of a log, that dictionary is real memory, and __slots__ = ("title", "priority", "status") removes it in exchange for closing the class: an attribute outside the declared names raises AttributeError. Tally does not need it, and it is worth choosing on purpose rather than reaching for by habit.
Dataclasses and the type hints that go with them
The hand-written class works, but it says nothing about what type each field is, and a Ticket with five fields needs a five-line __init__, an __eq__ and a __repr__ before it is pleasant to use. The dataclass decorator writes those from the field list:
from dataclasses import dataclass, field
from datetime import datetime, timezone
@dataclass
class Ticket:
id: int
title: str
body: str = ""
priority: str = "normal"
status: str = "open"
assignee: str | None = None
tags: list[str] = field(default_factory=list)
opened_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
t = Ticket(1, "Till 2 will not print receipts", priority="high")
print(t.status, t.assignee, t.tags) # open None []
print(t == Ticket(1, "Till 2 will not print receipts", priority="high", opened_at=t.opened_at)) # True
Three things in that block are easy to pass over. assignee: str | None = None says the field holds a string or nothing; the | form has been the plain way to write that since Python 3.10, and Optional[str] from typing means the same thing in older code. tags: list[str] = field(default_factory=list) is the class-attribute lesson again in different clothes: tags: list[str] = [] would be rejected by the dataclass machinery with a ValueError, precisely because a shared list is never what you mean, so the default is a function that makes a fresh one. And opened_at uses the same trick to stamp each ticket at creation rather than once at import.
The hints are not checks. Ticket("1", 42) runs without complaint, and nothing stops a caller passing priority="urgent" even though Tally has no such level. What the hints do is give a separate tool something to read: mypy or pyright flags Ticket("1", 42) before the program runs, an editor completes .title after t., and a reader six months on gets the contract without a comment that could go stale. In TypeScript the compiler does this job and refuses to build; in Python the checker is optional, which is why a team that wants the benefit runs it in continuous integration rather than trusting that everyone runs it locally.
For the two fields that must be one of a fixed set, a hint of str is too loose. The honest type is an enumeration:
from enum import Enum
class Priority(Enum):
LOW = "low"
NORMAL = "normal"
HIGH = "high"
class Status(Enum):
OPEN = "open"
IN_PROGRESS = "in_progress"
RESOLVED = "resolved"
CLOSED = "closed"
print(Priority("high")) # Priority.HIGH
print(Priority.HIGH.value) # high
try:
Priority("urgent")
except ValueError as e:
print(e) # 'urgent' is not a valid Priority
Now priority: Priority = Priority.NORMAL in the dataclass means the checker rejects a bare string, and Priority(text) at the edge of the service, where a request arrives, turns bad input into a ValueError at the one place it should be caught. The database chapter keeps the same shape: a choices list for the form and a check constraint for the table, two layers for one rule.
A namedtuple is the older cousin of a dataclass: named fields, immutable, hashable, still a tuple underneath. A dataclass is a plain mutable object unless you ask for @dataclass(frozen=True), which makes assignment raise and makes instances hashable again. Tally's Ticket changes status, so it stays mutable. A Priority value never changes, so the enum is the right shape for it.
Dunder methods: how a ticket prints, compares and sorts
When you wrote Ticket(...) and __init__ ran, you used a dunder method. Python reserves the double-underscore names for the methods it looks up by name when syntax needs to talk to an object: + looks for __add__, == for __eq__, len() for __len__, print() for __str__ and then __repr__. None of this is special-cased for your class; the syntax asks the object whether it defines the matching method and calls it if so.
| Syntax | Method Python looks for |
|---|---|
print(obj), str(obj) | __str__, falling back to __repr__ |
obj echoed in a shell, inside a list | __repr__ |
obj == other | __eq__ |
obj < other, sorted(objs) | __lt__ |
len(obj) | __len__ |
for x in obj | __iter__ |
x in obj | __contains__ |
with obj: | __enter__, __exit__ |
__repr__ and __str__ have different readers. __str__ is for the person reading the program's output: an agent looking at a queue should see #1 [high] Till 2 will not print receipts. __repr__ is for the person reading the code: in a shell, inside a printed list, in a stack trace, and anywhere __str__ is missing. The convention is that a repr is precise enough to rebuild the object. A dataclass writes __repr__ for you; write __str__ yourself when there is a human-facing form.
@dataclass
class Ticket:
id: int
title: str
priority: Priority = Priority.NORMAL
status: Status = Status.OPEN
def __str__(self):
return f"#{self.id} [{self.priority.value}] {self.title}"
t = Ticket(1, "Till 2 will not print receipts", Priority.HIGH)
print(t) # #1 [high] Till 2 will not print receipts
print([t]) # [Ticket(id=1, title='Till 2 will not print receipts', priority=<Priority.HIGH: 'high'>, status=<Status.OPEN: 'open'>)]
The generated __eq__ compares field by field, which is what you want for a value and rarely what you want for a record with an id. Two tickets with the same id are the same ticket even if one copy has a newer status. So Tally defines equality by id, and that decision has a consequence that catches people: defining __eq__ yourself sets __hash__ to None, because Python will not guess how to hash objects whose equality it did not write. A ticket then cannot go in a set or be a dictionary key until you define __hash__ to match.
@dataclass(eq=False)
class Ticket:
id: int
title: str
priority: Priority = Priority.NORMAL
status: Status = Status.OPEN
def __str__(self):
return f"#{self.id} [{self.priority.value}] {self.title}"
def __eq__(self, other):
return isinstance(other, Ticket) and self.id == other.id
def __hash__(self):
return hash(self.id) # consistent with __eq__: equal tickets hash alike
def __lt__(self, other):
order = {Priority.HIGH: 0, Priority.NORMAL: 1, Priority.LOW: 2}
return (order[self.priority], self.id) < (order[other.priority], other.id)
a = Ticket(1, "Till 2 will not print receipts", Priority.HIGH)
b = Ticket(1, "Till 2 will not print receipts", Priority.HIGH, Status.RESOLVED)
c = Ticket(2, "Cold room alarm sounding", Priority.LOW)
d = Ticket(3, "Staff login stopped working")
print(a == b, len({a, b, c})) # True 2
print([t.id for t in sorted([c, d, a])]) # [1, 3, 2]
__lt__ compares a tuple, which is the usual trick: high priority first, then the lower id first among equals. sorted only needs __lt__. The isinstance check in __eq__ matters because Python will try ticket == 5 and expects False, not an AttributeError. In Java this is equals and hashCode with the same rule that they agree; in TypeScript there is no operator overloading at all and a compare function is passed to sort, which is also a perfectly good Python design when the ordering is not a property of the ticket itself.
The in-memory store, and what carries forward
The ticket needs somewhere to live. Until chapter 04 that is a dictionary wrapped in a class that hides it, so the service code is written against methods rather than against the shape of the storage. Three dunders make the store read naturally:
class TicketStore:
def __init__(self):
self._by_id: dict[int, Ticket] = {}
self._next_id = 1
def open(self, title: str, priority: Priority = Priority.NORMAL) -> Ticket:
t = Ticket(self._next_id, title, priority)
self._by_id[t.id] = t
self._next_id += 1
return t
def get(self, ticket_id: int) -> Ticket | None:
return self._by_id.get(ticket_id)
def __len__(self):
return len(self._by_id)
def __iter__(self):
return iter(sorted(self._by_id.values())) # priority order, by __lt__
def __contains__(self, ticket_id):
return ticket_id in self._by_id
store = TicketStore()
store.open("Cold room alarm sounding", Priority.LOW)
store.open("Till 2 will not print receipts", Priority.HIGH)
store.open("Staff login stopped working")
print(len(store), 2 in store, 9 in store) # 3 True False
for t in store:
print(t)
# #2 [high] Till 2 will not print receipts
# #3 [normal] Staff login stopped working
# #1 [low] Cold room alarm sounding
print(store.get(9)) # None
The leading underscore on _by_id is a convention, not a lock: Python has no private fields, and store._by_id works from anywhere. What the underscore says is that the dictionary is an implementation detail that may change, and the Django chapter changes it, swapping the dictionary for a table while open, get, len and iteration keep their meaning. get returns None rather than raising, and that is a choice the chapter on views revisits: at the edge of a web service a missing ticket is a 404, and the method that raises is the right one there.
__iter__ returning a sorted copy is a small decision with a cost. Each loop sorts every ticket, which is fine for a few hundred and wrong for a million; the fix is an index, and chapter 04 makes the database do it. The point of writing the store this way now is that the sorting rule lives in one place, Ticket.__lt__, and everything that lists tickets inherits it.
Three habits from this chapter run through the rest of the track. Keep shared, never-mutated values on the class and everything else on the instance. Let a dataclass write the boring methods and an enum hold the fixed sets, so that a bad value fails at the edge rather than deep inside. And give objects a __str__ for people and leave __repr__ precise for the shell, because the first time you print a list of tickets at two in the morning, that is what you will read.