SOLID in Python With Protocol and ABCs: Five Small Refactors of One Bloated Ticket Service
One Help Desk TicketService with three jobs, cleaned up one SOLID letter at a time: split the jobs, add Slack without edits, an ABC that refuses a half-finished class, an SMS notifier that breaks its parent's promise, a Protocol that matches by shape, and mypy catching a wrong type on line 10.
What you will learn
- Split a class with three reasons to change (S)
- Add a new notifier without editing the service, using an ABC (O, L)
- Use small Protocols that match by shape (I) and depend on them (D)
- Choose between an ABC (checked when built) and a Protocol (checked by mypy)
Before you start
- Python classes and methods
- Type hints
Picture a cafe with one person doing everything: taking orders, cooking, handling the bill. The menu changes and everything stops while they relearn the kitchen. A new card machine arrives and everything stops again. Hire a cook and a cashier, and a change in one place no longer stops the others. One job per person means one reason to stop. That's the heart of SOLID.
SOLID isn't a library. It's five rules about where code should go and what it should depend on. In Python you don't need a framework for it: classes, an abstract base class (ABC) and a Protocol are enough. We'll clean up one bloated ticket service from a Help Desk app, one letter and one file at a time.
The bloated ticket service
class TicketService:
def __init__(self):
self.rows = {}
def open(self, title, plan):
# job 1: the SLA rule
if plan == "free":
hours = 48
elif plan == "pro":
hours = 8
else:
hours = 24
# job 2: storage
tid = len(self.rows) + 1
self.rows[tid] = (title, hours)
# job 3: telling the team
print(f"EMAIL to support: #{tid} {title}")
return tid, hours
svc = TicketService()
print(svc.open("Login fails", "pro"))
EMAIL to support: #1 Login fails
(1, 8)
It works. But support wants new SLA hours, we want Postgres, and the team wants Slack. Three different requests, and all three land on this one class. Three reasons to change in one class: that's the smell.
S: one reason to change
The single responsibility principle: a class should have one reason to change. In srp.py, each job gets its own home:
class TicketStore:
def __init__(self):
self.rows = {}
def add(self, title, hours):
tid = len(self.rows) + 1
self.rows[tid] = (title, hours)
return tid
def sla_hours(plan):
if plan == "free":
return 48
if plan == "pro":
return 8
return 24
class EmailNotifier:
def send(self, msg):
print(f"EMAIL to support: {msg}")
class TicketService:
def __init__(self, store, notifier):
self.store = store
self.notifier = notifier
def open(self, title, plan):
hours = sla_hours(plan)
tid = self.store.add(title, hours)
self.notifier.send(f"#{tid} {title}")
return tid, hours
if __name__ == "__main__":
svc = TicketService(TicketStore(), EmailNotifier())
print(svc.open("Login fails", "pro"))
EMAIL to support: #1 Login fails
(1, 8)
Same output as before. TicketService now only runs the steps in order, and gets the store and the notifier in its constructor. A refactor changes the shape, never the result.
O: add without editing
The open/closed principle: open for extension, closed for modification. In ocp.py, Notifier becomes an abstract base class:
from abc import ABC, abstractmethod
from srp import TicketStore, sla_hours
class Notifier(ABC):
@abstractmethod
def send(self, msg: str) -> None: ...
class EmailNotifier(Notifier):
def send(self, msg):
print(f"EMAIL to support: {msg}")
class SlackNotifier(Notifier): # the new class
def send(self, msg):
print(f"SLACK #helpdesk: {msg}")
class TicketService:
def __init__(self, store, notifiers):
self.store = store
self.notifiers = notifiers
def open(self, title, plan):
hours = sla_hours(plan)
tid = self.store.add(title, hours)
for n in self.notifiers:
n.send(f"#{tid} {title}")
return tid, hours
if __name__ == "__main__":
team = [EmailNotifier(), SlackNotifier()]
svc = TicketService(TicketStore(), team)
print(svc.open("Login fails", "pro"))
EMAIL to support: #1 Login fails
SLACK #helpdesk: #1 Login fails
(1, 8)
The service takes a list of notifiers and calls send on each one. Adding Slack then meant adding a class, and TicketService didn't change for it.New behaviour comes in as new code, not edits to old code.
What the ABC guarantees
In abc_guard.py, a notifier names its method page instead of send:
from ocp import Notifier
class PagerNotifier(Notifier):
def page(self, msg): # should be send
print(f"PAGER: {msg}")
try:
PagerNotifier()
except TypeError as err:
print(err)
Can't instantiate abstract class PagerNotifier without an implementation for abstract method 'send'
The mistake shows up when the object is created, not later in the middle of handling a customer's ticket. An ABC is a promise checked when the object is built.
L: keep the promise
The Liskov substitution principle: any subclass should work wherever its parent works.
from ocp import Notifier, TicketService
from srp import TicketStore
class SmsNotifier(Notifier):
def send(self, msg):
if len(msg) > 20:
raise ValueError("sms: max 20 chars")
print(f"SMS: {msg}")
class FitSmsNotifier(Notifier):
def send(self, msg):
print(f"SMS: {msg[:20]}")
for n in (SmsNotifier(), FitSmsNotifier()):
svc = TicketService(TicketStore(), [n])
try:
print(svc.open("Login fails after reset", "pro"))
except ValueError as err:
print("crash:", err)
crash: sms: max 20 chars
SMS: #1 Login fails after
(1, 8)
The parent never said there was a length limit. SmsNotifier quietly added one and broke the promise, so the service crashes. FitSmsNotifier accepts any message and trims it. A subclass can do more, but it can't demand more.
I: ask only for what you use
The interface segregation principle: don't make code depend on methods it never uses. In isp.py, reading and writing become two small Protocols:
from typing import Protocol, runtime_checkable
@runtime_checkable
class TicketReader(Protocol):
def all(self) -> list[tuple[str, int]]: ...
class TicketWriter(Protocol):
def add(self, title: str, hours: int) -> int: ...
class CsvExport: # no base class at all
def all(self) -> list[tuple[str, int]]:
return [("Login fails", 8), ("Refund", 48)]
def urgent(reader: TicketReader) -> list[str]:
return [t for t, h in reader.all() if h <= 8]
src = CsvExport()
print(isinstance(src, TicketReader))
print(urgent(src))
True
['Login fails']
urgent only reads, so it asks for a TicketReader and nothing more. CsvExport inherits from nothing, yet isinstance says True: a Protocol matches by shape, not by family tree. One thing to know: @runtime_checkable only checks that the method names exist. The full type check comes from a type checker.
D: depend on the idea, not the tool
The dependency inversion principle: high-level code depends on an abstraction, not on a concrete tool. In dip.py, Notifier is a Protocol with one method:
from typing import Protocol
from srp import TicketStore, sla_hours
class Notifier(Protocol):
def send(self, msg: str) -> None: ...
class TicketService:
def __init__(self, store: TicketStore,
notifier: Notifier) -> None:
self.store = store
self.notifier = notifier
def open(self, title: str, plan: str) -> int:
tid = self.store.add(title, sla_hours(plan))
self.notifier.send(f"#{tid} {title}")
return tid
class FakeNotifier: # a test double
def __init__(self) -> None:
self.sent: list[str] = []
def send(self, msg: str) -> None:
self.sent.append(msg)
if __name__ == "__main__":
fake = FakeNotifier()
svc = TicketService(TicketStore(), fake)
svc.open("Refund", "free")
print(fake.sent)
['#1 Refund']
The service doesn't know about email, Slack or anything else. In a test, a FakeNotifier stores each message in a list, so no email server is needed. The service owns the idea; the tools plug in from outside. That's the same flip of the arrow you see at app size in hexagonal architecture.
Caught before it runs
dip_bad.py passes something with the wrong shape:
from dip import TicketService
from srp import TicketStore
class Pager:
def page(self, msg: str) -> None:
print(f"PAGER: {msg}")
svc = TicketService(TicketStore(), Pager())
svc.open("Refund", "free")
Plain Python accepts the object and fails later, inside open:
AttributeError: 'Pager' object has no attribute 'send'
Run mypy on the same file and it reports the problem on line 10, where the service is built, before a single line has run:
mypy dip_bad.py
dip_bad.py:10: error: Argument 2 to "TicketService" has incompatible type "Pager"; expected "Notifier" [arg-type]
Found 1 error in 1 file (checked 1 source file)
With a Protocol, the type checker is the guard.
ABC or Protocol
| ABC | Protocol | |
|---|---|---|
| Matches by | Inheritance | Shape |
| Checked | When the object is built | By the type checker (mypy) |
| Choose it when | You own the classes and want shared code, or want Python to refuse a half-finished subclass | The classes come from a library or a test fake and you can't, or don't want to, make them inherit |
| In this project | The Notifier family | The CsvExport reader |
Both describe a set of methods. They just check it at different times.
The trade-off, and how to say it
Every interface is one more thing to read. If there's only ever one notifier, an ABC around it is just extra code. Add the abstraction when the second case appears, or when a test needs a fake.
In an interview, use three steps. Smell: one class with three reasons to change. Move: split the jobs and make the service depend on a small Protocol or ABC. Payoff: new notifiers without edits, and tests without an email server.
Recap
| Letter | Rule | File |
|---|---|---|
| S | One reason to change: split the jobs | srp.py |
| O | Add new classes, don't edit old ones | ocp.py |
| L | A subclass keeps its parent's promise | lsp.py |
| I | Small interfaces, easy to satisfy and fake | isp.py |
| D | Depend on the idea, not the tool | dip.py |
Try it yourself
Add a TeamsNotifier to ocp.py without touching TicketService. Then make one version that forgets send and check that the ABC refuses it.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Class Methods, Static Methods and Properties: What Each One Receives
Instance methods get self, class methods get cls, static methods get nothing. Then properties, setters and deleters, with small runnable files and their real output.
Python Classes and Objects: __init__, self and PEP 8 Names
A class is the blueprint and an object is what you build from it. Car, Student, Dog, Circle and BankAccount show what __init__ and self really do, how attribute lookup works, the missing self error, and PEP 8 names.
Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
A child class gets everything from its parent, Python walks up and stops at the first match, and super() reaches the parent. Then polymorphism: one call, a different method for each object, with Animal, Employee and Shape examples and their real output.
Python Multiple Inheritance, the MRO and Mixins
A class can have two parents or a whole chain of them, and one list puts them in order: the MRO. Read it, watch Python walk it, see super() follow it, and build JsonMixin and LogMixin for a User class.
