Sub topic 10
How languages express ADTs: interfaces, abstract classes, and modules
This chapter assumes you know Python classes and exceptions, and that you have seen the Stack specification and its two implementations from earlier chapters. Here we look at the language features that let you write the interface down and have the language help enforce it.
What a language can and cannot do for you
An abstract data type (ADT) is a set of operations plus the behavior they promise. A language can help in two ways:
- Name the operations. The language gives you a place to write the signatures separately from the code that stores data.
- Hide the representation. The language, or a convention, keeps clients from touching the fields.
No mainstream language can check the behavior itself. A compiler can confirm that pop exists. It cannot confirm that pop returns the last pushed item. That promise stays in your docstrings and your tests.
Mechanism 1: abstract base classes
Python's abc module lets a class declare methods that subclasses must supply. The Stack class from the earlier chapter uses this. The check happens when you create an object, not when you define the class.
from abc import ABC, abstractmethod
class Stack(ABC):
@abstractmethod
def push(self, item):
"""Add item to the top of the stack."""
@abstractmethod
def pop(self):
"""Remove and return the top item."""
class HalfStack(Stack):
def push(self, item):
pass # pop is missing
for cls in (Stack, HalfStack):
try:
cls()
except TypeError:
print(cls.__name__, "cannot be instantiated")Both attempts fail. Stack has no implementation at all, and HalfStack is missing pop. This is the main benefit of an abstract base class: a partly implemented ADT cannot be used by accident.
An abstract base class also lets you share code. A method that is not marked abstract can be written once in terms of the abstract operations, and every subclass inherits it.
from abc import ABC, abstractmethod
class Stack(ABC):
@abstractmethod
def pop(self):
"""Remove and return the top item."""
@abstractmethod
def is_empty(self):
"""Return True if the stack has no items."""
def drain(self):
"""Pop everything and return the items in pop order."""
out = []
while not self.is_empty():
out.append(self.pop())
return outdrain works for any subclass because it uses only operations from the interface.
Limits of abstract classes
- The check covers names only. It does not check argument counts, return values, or exceptions.
- An abstract method may have a body, and a subclass can call it through
super(). Do not rely on that for specification text. Put the promises in docstrings. - Inheritance ties each implementation to the base class. That is fine for code you own. It is awkward for a class from a library that you cannot edit.
Mechanism 2: protocols and duck typing
Python also accepts "structural" interfaces. An object satisfies the interface if it has the right methods, whether or not it inherits from anything. A typing.Protocol writes that interface down so a type checker such as mypy can verify it.
from collections import deque
from typing import Protocol, runtime_checkable
@runtime_checkable
class StackLike(Protocol):
def push(self, item): ...
def pop(self): ...
def is_empty(self): ...
class DequeStack:
"""Does not inherit from anything."""
def __init__(self):
self._items = deque()
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def is_empty(self):
return not self._items
def drain(stack):
out = []
while not stack.is_empty():
out.append(stack.pop())
return out
s = DequeStack()
s.push(1)
s.push(2)
print(isinstance(s, StackLike)) # True
print(drain(s)) # [2, 1]DequeStack never mentions StackLike, yet it fits. This is useful when the implementation comes from code you did not write.
Be careful with runtime_checkable. isinstance then checks only that the method names exist. It does not check signatures or behavior. The real checking comes from a static type checker, and only if you run one.
Mechanism 3: modules
An ADT does not need a class. A module can export a small set of functions and keep everything else private. The functions take a value of the hidden type as an argument. This style is the usual one in C, in Go packages, and in OCaml, where a module signature lists exactly what clients may see.
Here is a counter written as a Python module. Save it as counter.py:
"""A counter ADT. Clients use new(), increment(), and value()."""
__all__ = ["new", "increment", "value"]
class _Counter:
def __init__(self):
self.count = 0
def new():
return _Counter()
def increment(c):
c.count += 1
def value(c):
return c.countA client in the same folder uses only the three exported functions:
import counter
c = counter.new()
counter.increment(c)
counter.increment(c)
print(counter.value(c)) # 2If the author later stores the count in a file, a database, or a list, the client does not change. In this style the type name _Counter is hidden by convention, and the exports are the interface.
Hiding the representation
Naming operations is half the job. The other half is keeping clients away from the fields. Languages differ a great deal here.
| Language | Interface mechanism | How the representation is hidden | Enforced by |
|---|---|---|---|
| Python | `ABC`, `Protocol`, module `__all__` | Leading underscore on names | Convention and linters |
| Java | `interface`, abstract class | `private` fields | Compiler |
| C | Header file with opaque `struct` pointer | Struct body defined only in the `.c` file | Compiler and linker |
| OCaml | Module signature | Abstract type in the signature | Compiler |
| Go | Interface type, package | Lowercase identifiers are unexported | Compiler |
Python is the weakest here. A leading underscore tells readers "do not touch", but nothing stops stack._items.append(5). Python's double-underscore names (__items) are renamed internally to _ClassName__items. This prevents accidental name clashes in subclasses. It does not protect the data.
Interface versus abstract class versus module: choosing
The three mechanisms answer different needs.
- Use an abstract base class when you own all the implementations and want shared helper methods and early failure for incomplete subclasses.
- Use a protocol when implementations may come from other libraries, or when you want clients to be checked by a type checker without forcing inheritance.
- Use a module when there will be one implementation for now and you want the smallest possible surface. You can still replace the module's internals later.
You can combine them. A common pattern is a protocol for client type hints, an abstract base class for the implementations you write, and a module that exports a factory function.
def make_stack(kind="list"):
"""Factory: clients ask for a stack, not for a class."""
if kind == "list":
return ListStack()
if kind == "linked":
return LinkedStack()
raise ValueError(f"unknown stack kind: {kind}")This assumes ListStack and LinkedStack from the earlier chapters are in scope. A client that calls make_stack() never names a concrete class, so you can change the default later without touching the client.
Common errors
- Believing the abstract class checks behavior. It checks that methods exist. A
popthat returns the wrong item passes. Only tests catch that, as the final chapter shows. - Forgetting that the check runs at instantiation. A subclass with a missing method imports fine and fails only when someone creates an object. Keep a test that creates one object of each implementation.
- Writing clients against a concrete class. If a client calls
LinkedStack()directly, or readsstack._head, it is no longer independent of the representation. Take the stack as an argument or call a factory. - Trusting
isinstancewith a runtime-checkable protocol. It proves names exist, not that the object keeps the promises. - Leaving the specification only in code. A signature does not say that
popraisesIndexErroron an empty stack. Write that in the docstring.
Exercise
A teammate defines class FastStack: with push, pop, peek, and is_empty. It does not inherit from Stack. A function drain(stack: Stack) calls only is_empty and pop. Will drain(FastStack()) run, and what would make you still prefer to make FastStack inherit from Stack or a protocol?
Show answer
It will run, because Python looks up methods by name at call time and FastStack has the ones drain uses. Inheriting from Stack makes Python raise TypeError at instantiation if a method is later removed or misspelled. Declaring a Protocol lets a type checker flag a mismatch before the program runs. Without either, a missing method fails only when drain reaches that call.
Exercise
You add a module bag.py that exports new, add, and count, and a client calls bag.new()._items.sort(). Which part of the ADT idea does the client break, and what in the module would signal that this use is not allowed?
Show answer
The client reaches into the representation instead of using the exported operations, so it now depends on _items being a list. If the author changes the storage, the client breaks. The signals are the leading underscore on _items, the __all__ list that omits any sorting operation, and a docstring that names the exported functions as the interface.