Skip to content
Python

Python Composition, ABCs and Protocols: Designing Classes

Ihsan Ullah · 15 min read
Composition, ABCs and Protocols, Lesson 43 of the Python course: Designing classes that work together

Python course · Module 8: OOP in Python · Lesson 43 of 63

Quick answer: Composition means one object has other objects and uses them, like a cart that has a discount object. An abstract base class (ABC) is a parent class that lists methods every subclass must write; Python refuses to create objects that miss one. A Protocol describes the methods an object needs, such as pay(), without any inheritance; a type checker like mypy then accepts any class that has them.

In this lesson you will learn:

  • what composition is and why “has a” is often better than “is a”
  • how to write an abstract base class with ABC and @abstractmethod
  • what duck typing is
  • how typing.Protocol and @runtime_checkable work, and what mypy adds
  • how to choose between composition, ABCs and Protocols

Before you start: finish Lesson 42, Python dataclasses: Write Classes With Less Code. You need classes and methods from Lesson 38. All examples were run on Linux with Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org.

Composition: an object that has other objects

Inheritance (Lesson 40) says “a CardPayment is a PaymentMethod“. Composition says “a ShoppingCart has products and has a discount”. The cart keeps those objects in its attributes and asks them to do their part of the work:

from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1

    def subtotal(self):
        return self.price * self.quantity


class NoDiscount:
    def apply(self, amount):
        return amount


class PercentOff:
    def __init__(self, percent):
        self.percent = percent

    def apply(self, amount):
        return round(amount * (100 - self.percent) / 100, 2)


class ShoppingCart:
    def __init__(self, owner, discount):
        self.owner = owner
        self.discount = discount   # the cart HAS a discount
        self.items = []            # the cart HAS products

    def add(self, product):
        self.items.append(product)

    def total(self):
        subtotal = sum(item.subtotal() for item in self.items)
        return self.discount.apply(subtotal)


cart = ShoppingCart("Amna", NoDiscount())
cart.add(Product("pen", 1.5, 6))
cart.add(Product("notebook", 3.0))
print(cart.total())

cart.discount = PercentOff(10)
print(cart.total())
12.0
10.8
  • Product is a dataclass from Lesson 42. The cart keeps them in self.items.
  • self.discount holds a discount object. total() does not calculate the discount itself; it calls self.discount.apply(subtotal). Passing work to another object like this is called delegation.
  • Changing cart.discount to PercentOff(10) changed the result from 12.0 to 10.8, without changing the ShoppingCart class at all.

Why not make ShoppingCart inherit from PercentOff? Because a cart is not a discount. With inheritance, every new kind of discount would need a new kind of cart. With composition you write a small new discount class and give it to any cart. Use inheritance for a real “is a” relation; use composition for “has a” and “uses a”.

Abstract base classes (ABCs)

Our shop takes payments in several ways, and every payment class must have a pay() method. An abstract base class writes that rule into code. The abc module docs describe ABC as “A helper class that has ABCMeta as its metaclass”, which means you create an ABC simply by inheriting from ABC:

from abc import ABC, abstractmethod


class PaymentMethod(ABC):
    @abstractmethod
    def pay(self, amount):
        """Take the money and return a short message."""

    def receipt_line(self, amount):
        return f"{type(self).__name__}: {self.pay(amount)}"


class CardPayment(PaymentMethod):
    def __init__(self, last4):
        self.last4 = last4

    def pay(self, amount):
        return f"paid {amount:.2f} with card ending {self.last4}"


class CashOnDelivery(PaymentMethod):
    def pay(self, amount):
        return f"pay {amount:.2f} in cash at the door"


for method in [CardPayment("4242"), CashOnDelivery()]:
    print(method.receipt_line(10.8))

print(isinstance(CashOnDelivery(), PaymentMethod))
CardPayment: paid 10.80 with card ending 4242
CashOnDelivery: pay 10.80 in cash at the door
True
  • @abstractmethod marks pay() as a method that subclasses must write. Its body is only a docstring, because the parent has no real way to pay.
  • An ABC can also have normal methods. receipt_line() is written once in the parent and works in every subclass, because it calls self.pay(), which each subclass provides.
  • type(self).__name__ is the name of the object’s class, so each line starts with the right name.
  • isinstance(..., PaymentMethod) is True, because CashOnDelivery inherits from it.

What an ABC protects you from

from abc import ABC, abstractmethod


class PaymentMethod(ABC):
    @abstractmethod
    def pay(self, amount):
        """Take the money and return a short message."""


class BankTransfer(PaymentMethod):
    def pay_now(self, amount):          # wrong name: should be pay
        return f"sent {amount:.2f} by bank transfer"


print("The classes were created without errors.")

try:
    PaymentMethod()
except TypeError as err:
    print("TypeError:", err)

try:
    BankTransfer()
except TypeError as err:
    print("TypeError:", err)
The classes were created without errors.
TypeError: Can't instantiate abstract class PaymentMethod without an implementation for abstract method 'pay'
TypeError: Can't instantiate abstract class BankTransfer without an implementation for abstract method 'pay'

The docs explain the rule: “A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden.” So:

  • PaymentMethod() fails: the parent itself is not complete.
  • BankTransfer named its method pay_now by mistake, so pay is still missing. Note when the error happens: Python created both classes without complaint, and the error came only when we tried to create a BankTransfer object. The message names the missing method, which makes the typo easy to find.

ABCs come from PEP 3119, written for Python 3.0, which says “ABCs are simply Python classes that are added into an object’s inheritance tree”.

Duck typing: no parent class needed

Python does not check types before calling a method. It just calls it:

class CardPayment:
    def pay(self, amount):
        return f"paid {amount:.2f} by card"


class GiftCard:                         # no shared parent class
    def __init__(self, balance):
        self.balance = balance

    def pay(self, amount):
        self.balance -= amount
        return f"paid {amount:.2f} by gift card, {self.balance:.2f} left"


class Voucher:                          # has no pay() method
    def __init__(self, code):
        self.code = code


def checkout(total, payment):
    print(payment.pay(total))


checkout(10.8, CardPayment())
checkout(10.8, GiftCard(50.0))
checkout(10.8, Voucher("EID20"))
paid 10.80 by card
paid 10.80 by gift card, 39.20 left
Traceback (most recent call last):
  File "/home/learner/python-course/w42/step4_duck_typing.py", line 26, in <module>
    checkout(10.8, Voucher("EID20"))
    ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/learner/python-course/w42/step4_duck_typing.py", line 21, in checkout
    print(payment.pay(total))
          ^^^^^^^^^^^
AttributeError: 'Voucher' object has no attribute 'pay'

CardPayment and GiftCard share no parent class, but both have pay(), so checkout() works with both. Voucher has no pay(), so the call fails with AttributeError, but only when that line runs.

This is duck typing. The Python glossary describes it as a style that “does not look at an object’s type to determine if it has the right interface; instead, the method or attribute is simply called or used (‘If it looks like a duck and quacks like a duck, it must be a duck.’)”. It fits the EAFP style from Lesson 35: try the call and handle the error.

Duck typing is flexible, but the mistake with Voucher is found late, when a customer is already checking out.

Protocols: duck typing that a type checker understands

A Protocol from the typing module writes down what “has the right interface” means. Payer says: “an object with a pay(amount: float) -> str method”. The parts after the colons and after -> are type hints: notes about which types go in and come out. The body ... (an ellipsis) means “nothing here”:

from typing import Protocol


class Payer(Protocol):
    def pay(self, amount: float) -> str:
        ...


class CardPayment:
    def pay(self, amount: float) -> str:
        return f"paid {amount:.2f} by card"


class GiftCard:
    def __init__(self, balance: float) -> None:
        self.balance = balance

    def pay(self, amount: float) -> str:
        self.balance -= amount
        return f"paid {amount:.2f} by gift card, {self.balance:.2f} left"


class Voucher:
    def __init__(self, code: str) -> None:
        self.code = code


def checkout(total: float, payment: Payer) -> None:
    print(payment.pay(total))


checkout(10.8, CardPayment())
checkout(10.8, GiftCard(50.0))
checkout(10.8, Voucher("EID20"))
paid 10.80 by card
paid 10.80 by gift card, 39.20 left
Traceback (most recent call last):
  File "/home/learner/python-course/w42/step5_protocol.py", line 34, in <module>
    checkout(10.8, Voucher("EID20"))
    ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/learner/python-course/w42/step5_protocol.py", line 29, in checkout
    print(payment.pay(total))
          ^^^^^^^^^^^
AttributeError: 'Voucher' object has no attribute 'pay'

The program prints the same two lines and stops with the same AttributeError as before. Python itself still does not check: the typing docs say “The Python runtime does not enforce function and variable type annotations.” The value of a Protocol shows when you run a type checker, a tool that reads your code without running it. We installed mypy in a virtual environment (Lesson 30) with pip install mypy (Lesson 29), which gave mypy 2.4.1, and checked the same file with the command mypy step5_protocol.py:

step5_protocol.py:34: error: Argument 2 to "checkout" has incompatible type "Voucher"; expected "Payer"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

mypy found the Voucher mistake on line 34 before the program ran. It also accepted CardPayment and GiftCard, although neither of them inherits from Payer. Having a matching pay() method is enough. PEP 544 calls this “structural subtyping (static duck typing)”, and says that subclassing a protocol is “not necessary” for type checking. The mypy docs explain the other style: “Nominal subtyping is strictly based on the class hierarchy”, which is how ABCs work.

Python ABC vs Protocol diagram from Lesson 43: on the left CardPayment and CashOnDelivery inherit from the abstract base class PaymentMethod, and BankTransfer without pay() cannot be created; on the right CardPayment and GiftCard match the Payer protocol without inheritance, and mypy rejects Voucher.
An ABC checks subclasses when objects are created; a Protocol accepts any class with the right methods, and a type checker does the checking.

isinstance() with @runtime_checkable

A normal Protocol cannot be used with isinstance(). Add @runtime_checkable if you need that check while the program runs:

from typing import Protocol, runtime_checkable


@runtime_checkable
class Payer(Protocol):
    def pay(self, amount: float) -> str:
        ...


class GiftCard:
    def pay(self, amount: float) -> str:
        return f"paid {amount:.2f} by gift card"


class Voucher:
    pass


class BrokenWallet:
    def pay(self) -> str:               # forgot the amount parameter
        return "paid"


print(isinstance(GiftCard(), Payer))
print(isinstance(Voucher(), Payer))
print(isinstance(BrokenWallet(), Payer))
print(BrokenWallet().pay(10.8))
True
False
True
Traceback (most recent call last):
  File "/home/learner/python-course/w42/step6_runtime_checkable.py", line 27, in <module>
    print(BrokenWallet().pay(10.8))
          ~~~~~~~~~~~~~~~~~~^^^^^^
TypeError: BrokenWallet.pay() takes 1 positional argument but 2 were given
  • GiftCard passes and Voucher fails, with no inheritance at all.
  • BrokenWallet passes too, although its pay() takes no amount, and the real call then fails. The typing docs warn that runtime_checkable “will check only the presence of the required methods or attributes, not their type signatures or types”. Use it as a quick check, not as a guarantee.

Ready-made ABCs in collections.abc

Python ships many small ABCs in collections.abc. Several of them check for a method, a bit like a runtime Protocol. Sized is the “ABC for classes that provide the __len__() method”:

from collections.abc import Sized


class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self.items = ["pen", "notebook"]

    def __len__(self):
        return len(self.items)


cart = ShoppingCart("Amna")
print(len(cart))
print(isinstance(cart, Sized))
print(isinstance("pen", Sized), isinstance(42, Sized))
2
True
True False

Our cart has __len__, so it counts as Sized without inheriting from it. A string is Sized; the number 42 is not. Iterable and Iterator from the same module are the subject of the next lesson.

Composition, ABC or Protocol: which one to use?

ToolUse it whenChecked by
Compositionan object needs the help of another object (“has a”)nothing extra; it is plain attributes
ABCyou own the parent class, want to share code, and want to block incomplete subclassesPython, when an object is created
Protocolmany unrelated classes (or classes you do not own) should be accepted if they have the right methodsa type checker such as mypy

These tools work together. In our shop, the cart uses composition to hold a payment object, and that payment can be described by an ABC (if all payment classes are yours) or by a Protocol (if some come from other code). Start with composition and plain classes, and add an ABC or a Protocol when several classes must follow the same rules.

Try it yourself

Exercise 1: An order with shipping

Write StandardShipping (cost 2.0) and ExpressShipping (cost 5.0), each with a cost() method. Write an Order that has a customer name, a shipping object and a list of prices, with total() = sum of prices + shipping cost. Show the total for Bilal (prices 9.0 and 3.0) with both shipping methods.

Exercise 2: An abstract notifier

Write an ABC Notifier with an abstract send(message) method. Write EmailNotifier and SmsNotifier, send “Your order has shipped” with each, then show what happens when you try Notifier().

Exercise 3: Anything with a price

Write a @runtime_checkable Protocol Priced with one attribute, price: float. Write a function cheapest(things) that returns the thing with the lowest price. Test it with a list that holds Product dataclasses and a GiftCard class, which share no parent. Check each item and the string "pen" with isinstance(..., Priced).

Solutions

Solution 1

class StandardShipping:
    def cost(self):
        return 2.0


class ExpressShipping:
    def cost(self):
        return 5.0


class Order:
    def __init__(self, customer, shipping):
        self.customer = customer
        self.shipping = shipping   # the order HAS a shipping method
        self.prices = []

    def add(self, price):
        self.prices.append(price)

    def total(self):
        return sum(self.prices) + self.shipping.cost()


order = Order("Bilal", StandardShipping())
order.add(9.0)
order.add(3.0)
print(order.customer, order.total())

order.shipping = ExpressShipping()
print(order.customer, order.total())
Bilal 14.0
Bilal 17.0

The order delegates the shipping cost to its shipping object, so changing that object changes the total from 14.0 to 17.0.

Solution 2

from abc import ABC, abstractmethod


class Notifier(ABC):
    @abstractmethod
    def send(self, message):
        """Send the message and return a short report."""


class EmailNotifier(Notifier):
    def send(self, message):
        return f"email: {message}"


class SmsNotifier(Notifier):
    def send(self, message):
        return f"sms: {message}"


for notifier in [EmailNotifier(), SmsNotifier()]:
    print(notifier.send("Your order has shipped"))

try:
    Notifier()
except TypeError as err:
    print("TypeError:", err)
email: Your order has shipped
sms: Your order has shipped
TypeError: Can't instantiate abstract class Notifier without an implementation for abstract method 'send'

Both subclasses write send(), so they can be created; the abstract parent cannot.

Solution 3

from dataclasses import dataclass
from typing import Protocol, runtime_checkable


@runtime_checkable
class Priced(Protocol):
    price: float


@dataclass
class Product:
    name: str
    price: float


class GiftCard:
    def __init__(self, price):
        self.price = price


def cheapest(things):
    return min(things, key=lambda thing: thing.price)


basket = [Product("bag", 20.0), GiftCard(10.0), Product("pen", 1.5)]
print(cheapest(basket))
print([isinstance(thing, Priced) for thing in basket])
print(isinstance("pen", Priced))
Product(name='pen', price=1.5)
[True, True, True]
False

A Protocol can list attributes as well as methods. min() takes a key function just like sorted(key=...) in Lesson 25, and it works for every object that has price.

Common mistakes

  • Creating an object of the ABC itself. PaymentMethod() gives TypeError: Can't instantiate abstract class PaymentMethod without an implementation for abstract method 'pay'. Create a subclass that writes pay().
  • A typo in the method name of a subclass. pay_now instead of pay gives the same error, naming BankTransfer, when you create the object. Read the method name in the message.
  • Forgetting to inherit from ABC. With only @abstractmethod and no (ABC), nothing is checked: our PaymentMethod() was created without error, and pay() silently returned None.
  • Using isinstance() with a normal Protocol. You get TypeError: Instance and class checks can only be used with @runtime_checkable protocols. Add @runtime_checkable, or leave the check to mypy.
  • Creating an object of a Protocol. Payer() gives TypeError: Protocols cannot be instantiated. A Protocol only describes other classes.

Frequently asked questions

What is the difference between an ABC and a Protocol in Python?

With an ABC you write yourself, like PaymentMethod, a class must inherit from it, and Python blocks objects of incomplete subclasses. (Some ready-made ABCs, like Sized, accept any class with the right method.) With a Protocol, a class only needs the right methods; no inheritance is needed, and the check is done by a type checker such as mypy, not by Python when it runs.

What is composition over inheritance?

It is the advice to build objects from smaller objects (“has a”) instead of long chains of parent classes (“is a”). Our cart has a discount object; to add a new discount, you write a small class instead of a new kind of cart.

Do I need mypy to use Protocols?

No. The code runs without it. But Python does not check type hints, so without a type checker a Protocol is mainly documentation. With mypy (or another checker, such as pyright) it finds missing methods before you run the program.

Summary

  • Composition: an object holds other objects in attributes and delegates work to them (“has a”).
  • An ABC (class X(ABC) with @abstractmethod) blocks objects of classes that miss an abstract method, and can share normal methods.
  • Duck typing calls methods without checking types; mistakes appear only when the code runs.
  • A typing.Protocol lists the methods an object needs; a type checker accepts any class that has them, without inheritance.
  • @runtime_checkable allows isinstance() with a Protocol, but it checks only that the names exist.

Next lesson

Next: Lesson 44, Python Iterators and the Iteration Protocol.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *