Abstraction exposes what an operation promises while leaving its implementation behind an interface.
Use abstract base classes where useful and distinguish requiring a method’s name from proving its behavior.
The billing loop depends on a
monthly_fee() operation, not on how a product calculates its fee. That separation
is an abstraction. An abstract base class can make a missing implementation fail
earlier, when an instance is requested. Learn exactly what this check catches,
then test the parts of the contract it cannot establish.

A contract with a hole in it
Three products, three monthly_fee() methods, one billing loop that never
asks which is which — the previous lesson's whole point. But it only works
because every product happens to have the method. Nothing wrote that
rule down, and nothing checked it. Ship a fourth product with the method
misspelled, and the billing loop finds out at month end, in production,
holding an object it cannot bill.
The abc module can catch this particular omission. Inherit from ABC and put
@abstractmethod immediately above the required method. This marks it as abstract;
the ... below is only a placeholder body and does not perform the check itself:
Product states a required operation. Current supplies a concrete implementation
of that name, so Current() is allowed. The subclass may also inherit a concrete
implementation from an intermediate base; each subclass need not rewrite it.
Preparing this topic’s interactive investigation…
Checked at the door — and it can carry real code too
Leave the hole unfilled and Python refuses to build the object at all:
from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def monthly_fee(self):
...
class Draft(Product):
pass
print(Draft().monthly_fee())Duck typing finds an absent operation at the call. Regular subclasses of this ABC are checked for unresolved abstract members when instantiated. That narrows one failure's location; it does not run the method or verify the fee calculation.
An abstract class isn't only holes — it can carry real, shared code that calls the holes it declares:
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
def describe(self):
return f"area {self.area()}"
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
print(Square(3).describe())An implemented name can still have the wrong contract
This product clears the abstract-method check. Predict which line will fail:
constructed appears first. ABC machinery sees that the abstract name has been
overridden; it does not compare method signatures or validate return values.
Changing the method to accept no extra argument but return "five" would pass
construction and the call, then fail when billing tries to add the result to a
number. Returning the number 500 instead of 5 might run without any exception
and still violate the agreed units.
These are three different checks: completeness of the declared implementation, call compatibility, and correct behavior. A static type checker can help with signatures and annotated return types; example-based tests and clear contracts are still needed for units, edge cases, and effects. The original ABC specification explicitly separates enforced structure from behavioral promises.
Do not turn every TypeError into “abstract class.” A broad try around both
construction and billing would mislabel the failure above. Keep the handled
operation as small as possible, as in the earlier exception examples.
The practice classes below deliberately use missing abstract methods; those
fixtures do not make TypeError a universal diagnosis of incompleteness.
Hiding the how
Now define a useful behavioral contract: get(key) returns the stored value or
None for a missing key, and lookup does not modify the store. For this example,
stored values are numbers, so None is unambiguous. Two stores can provide that
contract using different representations:
get_or only calls get; it never accesses rows. That is what lets both stores
reuse it. A stored 0 must remain 0, so it checks found is None rather than
using found or fallback. This is a contract detail, not a storage detail.
A database-backed implementation could preserve this caller if it preserved the
same behavior. Database timeouts, asynchronous calls, or a different missing-value
policy would need an explicit decision; inheritance does not make those differences
disappear. If None later becomes a valid stored value, the current contract can
no longer distinguish “stored None” from “missing.” Choose a distinct sentinel or
another result shape before extending it.
For an independent check, add the same "zero": 0 entry to both stores. Run each
through a common check that expects 1 for "a", 0 for "zero", and a supplied
fallback for an unknown key, then repeats those reads. Repeatability is evidence
that these reads did not consume entries. A third store must pass the same checks
without the checks inspecting .rows.
When not to reach for it
The billing loop can work through duck typing alone. Use ABC when shared base
behavior and an explicit required-implementation check are useful. A small function
accepting a compatible object does not automatically need a hierarchy.
For optional static checking without requiring inheritance,
typing.Protocol
describes a structural interface. Type annotations do not themselves enforce that
contract at runtime. Even an optional @runtime_checkable protocol checks attribute
presence, not complete signatures or behavior. Treat these tools as different
forms of evidence, not interchangeable guarantees.
Quick practice
Name the method wrong and you haven't implemented the contract — you've added an unrelated method and left the hole open:
TypeErrorRead the error — it names the method that's missing. Then make it print fee 0.0.
from abc import ABC, abstractmethod
class Handler(ABC):
@abstractmethod
def handle(self, x):
...
h = Handler()🎯 Your turn
Define an abstract Product with an abstract label() and a concrete
summary() returning f"{self.label()} account". Give Current and Savings
their labels; leave Draft without one. Write try_open(kind) returning that
product's summary, or "incomplete" if the class cannot be built:
try_open("current")→"current account"try_open("savings")→"savings account"try_open("draft")→"incomplete"
Hint — the failure is a TypeError, and it happens on Draft(), before any
method is called. Wrap the construction, not the summary().
Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below builds a store with two completely different insides, and a month-end run where a broken product never even reaches the list.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Define Shape(ABC) with an abstract area(). Define Square(Shape) built from a side, implementing area(). Write square_area(side) returning that area.
Define Report(ABC) with an abstract render(). Define Html(Report) implementing it, and Draft(Report) which does not. Write can_build(kind) returning True if the named class can be instantiated and False if it raises.
Define Exporter(ABC) with an abstract body() and a concrete document() returning f"<{self.body()}>". Define Csv(Exporter) whose body is "a,b" and Json(Exporter) whose body is '{"a": 1}'. Write documents() returning both documents as a list, Csv first.
Define Store(ABC) with an abstract get(key) and a concrete get_or(key, fallback) returning the fallback when get gives None. Define DictStore holding {"a": 1, "b": 2} in a dict and PairStore holding the same data as a list of pairs. Write lookup(backend, key) — "dict" or "pairs" — returning the value, or "missing".
Define Account(ABC) built from a balance, with an abstract monthly_fee() and a concrete after_month() returning the balance minus the fee, rounded to 2 decimals. Define Current (fee 5.0), Savings (fee 0.0) and Draft, which never implements the fee. Write run_month(entries) where entries look like [["current", 100]], returning each balance after the month — or "incomplete" for a product that cannot be built.