Python - Polymorphism

Overview

Estimated time: 20–30 minutes

Polymorphism allows code to work with objects of different types through shared interfaces or behaviors rather than concrete classes.

Learning Objectives

  • Understand duck typing and structural typing (Protocols).
  • Use Abstract Base Classes (ABC) to define interfaces.
  • Design for polymorphism with clear, minimal interfaces.

Examples

from abc import ABC, abstractmethod
from typing import Protocol

class Writer(Protocol):
    def write(self, data: str) -> int: ...

def save_text(w: Writer, text: str):
    w.write(text)

class FileWriter:
    def __init__(self, path: str): self.path = path
    def write(self, data: str) -> int:
        with open(self.path, 'w', encoding='utf-8') as f:
            return f.write(data)

save_text(FileWriter('out.txt'), 'hello')

Guidance & Patterns

  • Prefer small, behavior-focused protocols over deep class hierarchies.
  • Use ABCs when runtime enforcement or shared code is useful.

Best Practices

  • Type to interfaces (Protocols/ABCs), not implementations.
  • Keep interfaces minimal and orthogonal; document behavior contracts.

Exercises

  1. Define a Storage protocol and implement local and memory-backed versions; write tests against the protocol.
  2. Refactor a class hierarchy to use composition + protocols.