Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 149 ยท Object-Oriented Programming

Abstract Classes and Protocols

Define interfaces in Python with abstract base classes (abc), understand duck typing, and describe expected methods structurally with typing.Protocol.

As programs grow, you often write code that works with "anything that can do X": any shape that can compute its area, any storage backend that can save and load, any notifier that can send a message. The question is how to describe that "anything", and how to make sure the classes you plug in really can do X.

Python gives you three tools for this. Duck typing simply calls the method and trusts the object. Abstract base classes (from the abc module) let a base class declare required methods and refuse to create incomplete subclasses. Protocols (from typing) describe the required methods without any inheritance at all. This lesson shows each one and when to choose it.

Duck typing

"If it walks like a duck and quacks like a duck, it's a duck." Python doesn't care about an object's class when you call a method; it only cares that the method exists:

Python Duck typing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Duck and Robot share no base class, yet both work. That flexibility is one of Python's strengths: file objects, io.StringIO and many other types work together just because they share method names. The cost shows on the last line, which fails on purpose: you only find out that Rock can't speak when the code runs and crashes.

Abstract base classes

An abstract base class (ABC) defines a shared interface and refuses to be instantiated until every required method is implemented. Inherit from ABC and mark required methods with @abstractmethod:

Python An abstract base class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line fails on purpose: TypeError: Can't instantiate abstract class Shape.... An ABC is a blueprint, not a finished class. Abstract methods often have only a docstring as their body; that's valid Python and documents what implementations must do.

The base class can still contain real, shared code. describe() is written once in Shape and works for every subclass because it calls the abstract methods, which each subclass fills in. This combination of a fixed outline with pluggable steps is a classic design pattern.

Catching mistakes early

The real benefit of an ABC shows when a subclass forgets something. The error appears as soon as you try to create an object, not later when some rarely used code path calls the missing method:

Python A forgotten method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The ... (the Ellipsis value) is another common placeholder body for abstract methods. Both it and a docstring mean "no implementation here".

Tip: You can also combine @abstractmethod with @property, @classmethod or @staticmethod. Put @abstractmethod closest to the def, for example @property then @abstractmethod.

Built-in ABCs in collections.abc

The standard library ships ABCs for common interfaces in collections.abc: Iterable, Sequence, Mapping, Sized, Callable and many more. They're useful in isinstance() checks. Some of them even recognize classes that never inherited from them, just because they have the right methods:

Python collections.abc

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Countdown never mentions Iterable, yet isinstance says yes, because Iterable checks for an __iter__ method. This is duck typing made checkable, and it leads directly to protocols.

Protocols: structural typing

ABCs require inheritance. Sometimes you can't, or don't want to, change the classes involved: they come from another library, or forcing a shared base class would couple unrelated code. A Protocol describes the methods an object must have, and any class with those methods matches, no inheritance required. This is called structural typing:

Python typing.Protocol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Neither Button nor ProgressBar mentions Drawable. They match because they have a draw() method returning a string.

Protocols are mainly for type checkers such as mypy and for your editor. If you call render([42]), a type checker flags the error before you run anything, because int has no draw() method. At runtime, Python ignores the annotation. Adding @runtime_checkable lets you use the protocol in isinstance() too, but that check only confirms the method names exist; it doesn't check signatures or return types. You'll learn more about annotations in Type Hints.

Protocols with attributes and properties

A protocol can require data as well as methods. Annotate an attribute in the protocol body, such as name: str, and any class whose instances have a name string matches. A read-only @property in a protocol means "must have this attribute, at least for reading". This lets you describe things like "any object with a .price and a .quantity" without caring whether the object is a data class, a regular class or a named tuple.

A note on NotImplementedError

Before the abc module was common, base classes marked required methods by raising NotImplementedError in the body:

Python
class Exporter:
    def export(self, rows: list[dict]) -> str:
        raise NotImplementedError("subclasses must implement export()")

You'll still see this pattern. It works, but the error only appears when the method is called, not when the object is created, so an ABC gives earlier and clearer feedback. Don't confuse NotImplementedError (an exception) with NotImplemented (the value that special methods return for unsupported operand types).

Choosing between them

Tool Requires inheritance? Checked when? Good for
Duck typing No When the method is called Small scripts, flexible code
ABC Yes When an object is created Families of classes you own that share code
Protocol No By a type checker (and optionally isinstance) Interfaces across unrelated or third-party classes

A practical rule of thumb:

  • Start with plain duck typing.
  • Reach for an ABC when you control the subclasses and want a shared base with real code, plus a guarantee that every subclass is complete.
  • Reach for a Protocol when you want to describe "anything with these methods" for type checking, without forcing classes to inherit from you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens when you try to create an instance of a class that still has an unimplemented @abstractmethod?

    Instantiation fails with a TypeError that names the missing abstract methods, so mistakes show up early.
  2. 2. How does a class satisfy a typing.Protocol?

    Protocols use structural typing. Any class with matching methods fits, without inheriting from the protocol.
  3. 3. What does isinstance(obj, SomeProtocol) check when the protocol is @runtime_checkable?

    Runtime checks only look for the attribute names. Signatures and types are a job for static type checkers.
  4. 4. Which statement about duck typing is true?

    Python calls the method on whatever object it gets. A missing method causes an AttributeError at the moment of the call.

Summary

  • Duck typing: Python cares about what an object can do, not its class; missing methods fail at call time.
  • Abstract base classes (abc.ABC + @abstractmethod) define required methods; incomplete subclasses can't be instantiated.
  • ABCs can also hold shared, concrete methods that call the abstract ones.
  • collections.abc provides ready-made ABCs such as Iterable, Sequence and Mapping for isinstance() checks.
  • Protocols (typing.Protocol) describe required methods structurally; any matching class fits, and type checkers verify it.
  • @runtime_checkable enables isinstance() with a protocol, checking method names only.

Next: Enums, where you'll replace magic strings and numbers with named, type-safe constants.