Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • What @ Means in Python: Decorators Built by Hand, Then Shortened
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • SOLID in Python With Protocol and ABCs: Five Small Refactors of One Bloated Ticket Service
  • Strategy and Factory in Python: A dict Registry Instead of an if-elif Ladder
  • Adapter and Facade in Python: One Interface Over Three LLM Providers
  • Entities, Value Objects and Aggregates: One Root Guards the Rules, One Transaction Saves One Aggregate
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  • Python Decorators vs the Decorator Pattern vs Proxy: Same Shape, Different Job
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  1. Blog
  2. /
  3. Python
  4. /
  5. Object-Oriented Python

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Object-Oriented Python

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.

One class with three jobs, then one job each bloated.py SLA rule storage email TicketService sla_hours() TicketStore Notifier Email, Slack, fake
Three reasons to change in one class, then one home per job.

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

ABCProtocol
Matches byInheritanceShape
CheckedWhen the object is builtBy the type checker (mypy)
Choose it whenYou own the classes and want shared code, or want Python to refuse a half-finished subclassThe classes come from a library or a test fake and you can't, or don't want to, make them inherit
In this projectThe Notifier familyThe 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

LetterRuleFile
SOne reason to change: split the jobssrp.py
OAdd new classes, don't edit old onesocp.py
LA subclass keeps its parent's promiselsp.py
ISmall interfaces, easy to satisfy and fakeisp.py
DDepend on the idea, not the tooldip.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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 26 of 57

Previous
Python OOP Practice: Design a Bank, an Employee System and a Library
Next post
Strategy and Factory in Python: A dict Registry Instead of an if-elif Ladder

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.

On this page

  • The bloated ticket service
  • S: one reason to change
  • O: add without editing
  • What the ABC guarantees
  • L: keep the promise
  • I: ask only for what you use
  • D: depend on the idea, not the tool
  • Caught before it runs
  • ABC or Protocol
  • The trade-off, and how to say it
  • Recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.