๐Ÿ›๏ธABC, @abstractmethod, ProtocolLESSON

Abstract Classes: ABC, @abstractmethod, Protocol

As codebases grow, you need mechanisms to define contracts โ€” "any class that does X must implement Y". Python offers two approaches: ABC (Abstract Base Classes) for inheritance-based contracts, and Protocol for structural typing (duck typing with type safety).

ABC and abstractmethod

ABC from abc module is a base class that supports abstract methods. You can't instantiate a class with unimplemented abstract methods:

Concrete Subclasses Must Implement All Abstract Methods

A subclass becomes concrete (instantiatable) only when it provides implementations for all abstract methods:

@abstractproperty Pattern

Use @property combined with @abstractmethod to require properties in subclasses:

Protocol โ€” Structural Subtyping

Protocol (from typing) defines an interface by structure โ€” a class satisfies a Protocol if it has the right methods and attributes, regardless of its class hierarchy. No inheritance required:

@runtime_checkable Protocol

By default, Protocols only work with static type checkers. Add @runtime_checkable to enable isinstance() checks at runtime:

Note: @runtime_checkable only checks for the existence of methods, not their signatures.

ABC vs Protocol: When to Use Each

SituationUse
Shared implementation between subclassesABC
Enforcing that subclasses exist in the hierarchyABC
Defining an interface without restricting inheritanceProtocol
Cross-library duck typingProtocol
Third-party classes you can't modifyProtocol

Knowledge Check

What happens when you try to instantiate an abstract class directly?

What is the key difference between ABC and Protocol?

What does `@runtime_checkable` enable for a Protocol?