← Back to Python, page 3

python-0045 · Medium mid

How do abstract base classes and Protocols define interfaces in Python?

abc.ABC with @abstractmethod defines a base class that cannot be instantiated until subclasses implement the abstract methods, enforcing the interface at runtime. typing.Protocol describes an interface structurally: any class with matching methods satisfies it for type checkers, without inheriting, which fits duck typing.

Full answer
python
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable

class Notifier(ABC):
    @abstractmethod
    def send(self, to: str, msg: str) -> str: ...

class Email(Notifier):
    def send(self, to, msg): return f"email to {to}: {msg}"

class Broken(Notifier):
    pass

print(Email().send("asha@x.com", "hi"))
try:
    Broken()
except TypeError as e:
    print("TypeError:", e)

@runtime_checkable
class Sender(Protocol):
    def send(self, to: str, msg: str) -> str: ...

class Sms:
    def send(self, to, msg): return f"sms to {to}: {msg}"
print(isinstance(Sms(), Sender), isinstance(Sms(), Notifier))

Output:

text
email to asha@x.com: hi
TypeError: Can't instantiate abstract class Broken without an implementation for abstract method 'send'
True False

Instantiating Broken fails because it does not implement send; the error lists the missing method. Sms never inherits from anything, yet it satisfies the Sender protocol, and runtime_checkable allows an isinstance check that only verifies the method exists, not its signature. It is not a Notifier because ABCs require inheritance or registration. Use ABCs when you own the hierarchy and want shared code; use Protocols to type code that accepts any object with the right methods.

python
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable

class Notifier(ABC):
    @abstractmethod
    def send(self, to: str, msg: str) -> str: ...

class Email(Notifier):
    def send(self, to, msg): return f"email to {to}: {msg}"

class Broken(Notifier):
    pass

print(Email().send("asha@x.com", "hi"))
try:
    Broken()
except TypeError as e:
    print("TypeError:", e)

@runtime_checkable
class Sender(Protocol):
    def send(self, to: str, msg: str) -> str: ...

class Sms:
    def send(self, to, msg): return f"sms to {to}: {msg}"
print(isinstance(Sms(), Sender), isinstance(Sms(), Notifier))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • ABCs enforce abstract methods at instantiation
  • Protocols are structural
  • runtime_checkable checks method presence only
  • ABCs can share implementation
  • Protocols fit duck typing

Common mistakes

  • Expecting Protocols to be enforced at runtime by default
  • Deep ABC hierarchies for simple interfaces

Follow-ups

  • How does ABC.register work?
  • When would a Protocol be generic?

Tips

  • Contrast nominal and structural typing