Python Abstractions: Mastering Protocols and Abstract Base Classes
Overview of Abstraction Layers
Defining interfaces allows developers to create a contract between different parts of a software system. In
Prerequisites
To get the most out of this guide, you should understand
Key Libraries & Tools
- abc: The standard library module providing the
ABCclass andabstractmethoddecorator for defining formal interfaces. - typing: Contains the
Protocolclass and theruntime_checkabledecorator used for structural typing and runtime validation. - Pylance/Mypy: Essential static analysis tools that help catch interface mismatches before you ever run your code.
Code Walkthrough: Implementing ABCs
from abc import ABC, abstractmethod
class SerializedFileHandler(ABC):
def __init__(self, filename: str):
self.filename = filename
@abstractmethod
def serialize(self, data: dict) -> bytes:
"""Must be implemented by sub-classes."""
pass
def write(self, data: dict):
# Shared logic that uses the abstract method
content = self.serialize(data)
with open(self.filename, 'wb') as f:
f.write(content)
In this snippet, write is a concrete method. Any child class, like a JsonHandler, only needs to implement serialize. The ABC handles the file I/O logic, keeping your sub-classes lean.
Syntax Notes: The Power of Protocols
from typing import Protocol, runtime_checkable
@runtime_checkable
class Writable(Protocol):
def write(self, data: dict) -> None: ...
The ... (ellipsis) is standard syntax for protocol methods. The @runtime_checkable decorator is vital if you intend to use isinstance() checks later; without it,
Practical Examples
Use write() method, you can define a Writable
Tips & Gotchas
Don't rely solely on runtime checks for

Fancy watching it?
Watch the full video and context