Sub topic 6
A Worked Example: The Stack ADT
This chapter assumes you know basic Python classes, exceptions, and the idea of an abstract data type (ADT) from the earlier chapters. An ADT is defined by its operations and the behavior they promise, not by how it stores data. Here we apply that idea to one concrete type, the stack. We write down its operations, state its behavior precisely, turn the specification into an interface, and write a client that uses only that interface.
What a stack promises
A stack is a collection with last-in, first-out (LIFO) order. The item you added most recently is the first one you get back. A pile of plates works this way: you add to the top and take from the top.
Notice that this description says nothing about arrays, nodes, or memory. It only says what happens when you add and remove items. That is the level an ADT lives at.
The operations
The stack has four operations. They fall into the categories from the previous chapters.
| Operation | Category | Precondition | Result |
|---|---|---|---|
| `Stack()` (constructor) | Constructor | None | A new, empty stack |
| `push(item)` | Mutator | None | `item` becomes the top |
| `pop()` | Mutator and observer | Stack is not empty | Removes and returns the top item |
| `peek()` | Observer | Stack is not empty | Returns the top item, leaves the stack unchanged |
| `is_empty()` | Observer | None | `True` if the stack holds no items |
pop is both a mutator and an observer: it changes the stack and also reports a value. That is a deliberate convenience. Some ADT designs split it into peek plus a separate remove, and both designs are valid.
Specifying the behavior
A signature list is not enough. Two types can have identical method names and still behave differently, as a stack and a queue do. The behavior is what separates them. For the stack, we state it as axioms: facts that hold for every correct implementation.
- A newly constructed stack is empty.
- After
push(x), the stack is not empty. - After
push(x),peek()returnsx. push(x)followed bypop()returnsxand leaves the stack as it was before the push.pop()andpeek()on an empty stack raiseIndexError.
Axiom 4 is the one that makes the structure LIFO. Axiom 5 is the error case. The precondition "stack is not empty" says what the caller must guarantee. When the caller breaks it, the specification says exactly what happens: an IndexError. Without that rule, an empty-stack pop could return None, crash, or return garbage, and clients could not rely on any of them.
The stack's behavior can also be drawn as states, based only on whether it is empty.
The interface in code
An abstract base class lets Python record the operations and their promises without choosing a representation. The docstrings carry the specification.
from abc import ABC, abstractmethod
class Stack(ABC):
"""A last-in, first-out collection.
push(x) then pop() returns x.
pop() and peek() raise IndexError on an empty stack.
"""
@abstractmethod
def push(self, item):
"""Add item to the top of the stack."""
@abstractmethod
def pop(self):
"""Remove and return the top item."""
@abstractmethod
def peek(self):
"""Return the top item without removing it."""
@abstractmethod
def is_empty(self):
"""Return True if the stack has no items."""You cannot create a Stack directly. Python raises TypeError because the abstract methods have no implementation. That is the intended behavior: the interface is a contract, not a working object.
One implementation to run the examples
To run anything, we need a concrete class. Here is one, using a Python list with the end of the list as the top. The next chapter compares this with a second implementation, so for now treat it as a stand-in.
class ListStack(Stack):
def __init__(self):
self._items = []
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 peek(self):
if not self._items:
raise IndexError("peek at empty stack")
return self._items[-1]
def is_empty(self):
return not self._itemsThe leading underscore on _items signals that the list is private to the class. Clients should never touch it. Python does not stop them, so the convention is what keeps the abstraction intact.
A client that uses only the interface
A good client of an ADT calls only the specified operations. The function below checks whether brackets in a string are balanced. It receives a stack factory as a parameter, so it does not name any concrete class.
def is_balanced(text, make_stack):
closers = {")": "(", "]": "[", "}": "{"}
stack = make_stack()
for ch in text:
if ch in "([{":
stack.push(ch)
elif ch in closers:
if stack.is_empty() or stack.pop() != closers[ch]:
return False
return stack.is_empty()
print(is_balanced("{[()]}", ListStack)) # True
print(is_balanced("{[(])}", ListStack)) # False
print(is_balanced("((", ListStack)) # False
print(is_balanced(")", ListStack)) # FalseLook at how the function respects the precondition. Before it pops, it checks stack.is_empty(). The or short-circuits, so pop is never called on an empty stack. The final return stack.is_empty() catches unclosed openers such as "((".
This function would work unchanged with any other correct Stack. That property, client independence, is the payoff of the design.
Edge cases and design decisions
Several details in the specification are choices. Making them explicit is part of designing an ADT.
- Error signaling. We chose an exception for
popon an empty stack. ReturningNoneis the alternative, but it fails ifNoneis a legitimate item. A stack that holdsNonevalues would then be ambiguous. - Storing
None. Our stack allows it.push(None)followed bypop()returnsNone, andis_empty()isFalsein between. Because of this,is_emptyis the only reliable emptiness test. - Capacity. The specification does not mention a size limit, so clients may assume the stack is unbounded. A bounded stack would be a different ADT, with a
pushprecondition such as "stack is not full". - What is not promised. There is no
len, no iteration, and no way to read items below the top. A client that needs those operations needs a different ADT, or an extended one. Leaving them out is what keeps the stack small and its implementations free to vary. - Mutable items. The stack stores references. If a client pushes a list and later changes it, the stored item changes too. The stack's own behavior is still correct, but the client should know this.
Common mistakes
| Mistake | Why it is wrong |
|---|---|
| Using a plain Python `list` as the stack everywhere | A list is a data structure. It exposes insertion at any index and slicing, so clients can depend on operations a stack should not offer. |
| Calling `pop()` without checking `is_empty()` | Breaks the precondition and raises `IndexError` at runtime. |
| Writing `ListStack()` inside client code | Ties the client to one implementation. Pass in a factory or an existing stack instead. |
| Reading `stack._items` from outside the class | Depends on the representation. It breaks if the implementation changes. |
| Checking `if stack.pop() is None` to detect emptiness | Wrong on an empty stack, which raises an error. It is also ambiguous when `None` is a stored item. |
What carries forward
You now have the three parts of a worked ADT: a set of operations, a behavioral specification with preconditions and an error case, and a client written against the interface. The next chapter adds a second representation behind the same interface. The client code above stays exactly as written.
Exercise
A teammate changes Stack.pop so that popping an empty stack returns None instead of raising IndexError. Name two ways this breaks the ADT's contract or its clients, using the is_balanced function as one example.
Show answer
First, it changes the specification, so every client written against the old promise (axiom 5) can no longer rely on it. Second, None is a legal stored item, so a client cannot tell "the stack held None" from "the stack was empty". In is_balanced, the guard stack.is_empty() still protects the pop, so that function would keep working. Any client that relied on the exception to detect misuse would silently continue with a wrong value instead.