Lesson · Object-Oriented Python
Abstract Base Classes
55 min readAbstract Base Classes
Abstract base classes provide nominal contracts and optional shared behavior. They are useful when an ecosystem benefits from explicit registration or required methods, but they are not the only way to express interfaces.
Learning goals
- Explain what
from abc import ABC, abstractmethodimports and howclass Storage(ABC)changes instantiation. - Describe why
Storage()raisesTypeErrorwhileMemoryStorage()succeeds. - Read
@abstractmethodonsaveas a requirement a concrete subclass must override before it can be instantiated. - Predict what happens when
MemoryStorageforgetssave, and at which moment the error appears. - Compare the enforcement of an ABC with the permissiveness of duck typing for the same
savecontract.
Mental model
The ABC moves the contract check to construction time: Python looks at the set of abstract names and refuses to create an instance until every one is overridden. That is the trade: less flexibility than duck typing, but the error arrives before any object exists.
Mental model
read it top to bottom
class Storage(ABC) with @abstractmethod save ↓ attempt Storage() TypeError: can't instantiate abstract class (contract enforced) ↓ subclass MemoryStorage implements save MemoryStorage() works, and isinstance(x, Storage) succeeds ↓ subclass forgets save TypeError at instantiation, not at the first save() call
Core idea
An abstract base class is a nominal contract: you inherit from ABC, decorate required operations with @abstractmethod, and Python refuses to instantiate any class that still has unfulfilled abstract names. Unlike duck typing, the check happens at construction, so a missing method is caught before the object is used; unlike a protocol, the contract is tied to the class tree or an explicit registration. Use it when early enforcement and isinstance support are worth the inheritance coupling.
abc
abc is the standard-library module that provides the machinery behind abstract base classes: the ABC convenience base class, ABCMeta, and the abstractmethod decorator. Importing from it is the modern way to declare a base class that refuses instantiation until its abstract methods are implemented. Registered virtual subclasses and the abstract-name checking both live in this module.
ABC
ABC is a convenience base class whose metaclass is ABCMeta, the component that actually tracks abstract methods. Subclassing ABC marks the class as nominal: it can hold @abstractmethod declarations, and it supports isinstance checks that include registered virtual subclasses. Instantiating it, or any subclass that still has unimplemented abstract methods, raises TypeError.
@abstractmethod
@abstractmethod marks behavior that concrete subclasses must implement before instances can be created. It expresses a nominal contract through an abstract base class.
Nominal interface contracts
A nominal interface depends on explicit inheritance or registration. ABCs can provide this when runtime identity as part of an interface matters.
ABCs vs duck typing
An ABC is a nominal contract: subclasses inherit from it (or register), and a missing method stops instantiation with TypeError. Duck typing is structural: any object with the right operations qualifies, and mistakes surface at the call site instead. Choose the ABC when early enforcement, shared helper methods, or isinstance support matter across an ecosystem, and duck typing when the contract is simple and the inheritance coupling costs more than it buys.
Walkthrough
from abc import ABC, abstractmethodimports the base class and the decorator;class Storage(ABC)makesStorageabstract-capable and recordssavein its set of abstract names.- Calling
Storage()raisesTypeError: Can't instantiate abstract class Storage with abstract method save, because the check runs when the class is called, before any instance can escape. MemoryStoragedefinessave, which removes that name from the abstract set, soMemoryStorage()constructs normally,isinstance(MemoryStorage(), Storage)isTrue, and theraise NotImplementedErrorbody inStorage.saveis only a safety net.- Predict before running: what
Storage()raises, whatMemoryStorage().datastarts as, and what error you get after deletingMemoryStorage.save.
Experiments to try
- Call
Storage()and record the exactTypeError; then add a second abstract methodloadtoStorageand rerunMemoryStorage()to watch the error return for the unimplemented name. - Delete
MemoryStorage.saveand observe thatMemoryStorage()itself fails now, before anysavecall ever runs. - Print
Storage.__abstractmethods__for both classes and watch the set change from{'save'}tofrozenset(). - Define
class DuckStorewith asavemethod and callStorage.register(DuckStore); note thatissubclass(DuckStore, Storage)becomesTrueeven though no inheritance happened and nothing checked the method.
Common mistakes
- Assuming
@abstractmethodblocks the method from being called: the decorator only records the name, and enforcement happens at instantiation, so the body still runs if a subclass calls it withsuper().save(...). - Forgetting that abstractness belongs to the class: a subclass that inherits
savewithout overriding it stays abstract too, and instantiating that subclass raisesTypeError. - Expecting
Storage.registerto validate anything: it only records a virtual subclass forisinstanceandissubclass, so a registered class whose methods do not match the interface passes the check anyway. - Reaching for an ABC for a single simple contract: every implementation then has to inherit from the base, which costs flexibility that duck typing would have kept, so use it only when enforcement or
isinstancematters.
Practice: Easy
- Run
Storage()and record theTypeError; then instantiateMemoryStorage()and confirm which class succeeded and why. - Delete
MemoryStorage.save, rerun, and note where the error appears; restore it and state what the decorator had required of the subclass. - Print
Storage.__abstractmethods__before and after the subclass definition; explain why the subclass set is empty.
Practice: Medium
- Add a
load(self, key)abstract method toStorageand giveMemoryStoragean implementation returningself.data.get(key); use theTypeErrorfrom a partially updated subclass to find what is still missing. - Write a
DictStoragethat uses composition (it contains a dict) instead of inheriting fromStorage; list which parts of the contract the ABC was enforcing and what now depends only on convention. - Replace
Storagewith a plain functionsave_all(storage, items)that callsstorage.save(...)in a loop; state what is gained (no coupling) and lost (no early error) compared with the ABC.
Practice: Hard
- Design a
SerializerABC with abstractdumps(value)andloads(text)methods plus a concreteroundtrip(value)helper; implement two subclasses and write tests that also cover theTypeErrorfor a half-implemented subclass. - Build a failure lab: instantiate the ABC directly, half-implement a subclass, and register a class whose methods do not match the interface. For each, show the exact error or the silent gap and name the mechanism.
- Connect this lesson to the duck typing lesson: take
emitfrom that lesson and decide which of its informal requirements would gain something from an ABC, then argue both sides with a runnable example.
Lesson checklist
- I can say what
ABCandabstractmethoddo in one sentence each. - I can explain why
Storage()fails whileMemoryStorage()succeeds. - I can point to
__abstractmethods__and interpret the names in it. - I can describe what registration adds to
isinstanceand what it does not check.
Remember
An ABC turns a contract into a construction-time check: abstract names are recorded, and any class that still has them cannot be instantiated. That is stronger than duck typing for catching omissions early and weaker in flexibility, since implementations must join the class tree or register; the choice is between early errors and loose coupling for the specific contract.
Interview angles
What is the main purpose of **abc**?+
abc is the standard-library module that provides the machinery behind abstract base classes: the ABC convenience base class, ABCMeta, and the abstractmethod decorator. Importing from it is the modern way to declare a base class that refuses instantiation until its abstract methods are implemented. Registered virtual subclasses and the abstract-name checking both live in this module.
What should you pay attention to when using **ABC**?+
ABC is a convenience base class whose metaclass is ABCMeta, the component that actually tracks abstract methods. Subclassing ABC marks the class as nominal: it can hold @abstractmethod declarations, and it supports isinstance checks that include registered virtual subclasses. Instantiating it, or any subclass that still has unimplemented abstract methods, raises TypeError.
How does **@abstractmethod** fit into this lesson?+
@abstractmethod marks behavior that concrete subclasses must implement before instances can be created. It expresses a nominal contract through an abstract base class.
Why does `@abstractmethod` not prevent the decorated method from being called?+
The decorator records the name in the class's abstract set; enforcement happens when a class with a non-empty abstract set is instantiated, so the method body itself remains a normal function. A subclass can even call it deliberately with super().save(...), and the raise NotImplementedError line inside is a safety net rather than the mechanism.