Treating One Object and a Group Alike: The Composite Pattern in Python
This article explains how the Composite pattern gives single elements and nested groups one interface, how generators walk the resulting trees, where child management belongs, and how cycles and repeated aggregation are avoided.
Hierarchies such as folders and files, product bundles, organization charts and nested menus share a structure in which a container may hold single elements and other containers, to any depth. Code that handles them often checks, at every step, whether it is looking at one element or at a group, and repeats that check wherever the hierarchy is used. The present article examines the Composite pattern, which gives single elements and groups the same interface, so that a client asks a whole tree the same question that it asks one leaf. It builds a catalogue of products and nested bundles, walks a file tree with generators, discusses where the methods that manage children should live, identifies the pattern in the standard library and analyses the errors that cycles and repeated computation introduce. Asking a whole tree the same question as one of its leaves, without any check of which one it is, is the secret weapon of the Composite pattern.
Bags Within Bags: Composites That Contain Composites
The pattern distinguishes three roles: the component, which declares the common interface; the leaf, which implements it directly; and the composite, which holds children and implements the same interface by delegating to them. In the following example, a product is a leaf and a bundle is a composite, and a bundle may contain products and other bundles, each with its own discount; the component is an abstract base class, as described in the article devoted to abstract base classes. Prices are kept in cents, as integers, to avoid the rounding errors of binary floating point.
from abc import ABC, abstractmethod
class Item(ABC):
@abstractmethod
def price(self): ...
class Product(Item):
def __init__(self, name, cents):
self.name, self.cents = name, cents
def price(self):
return self.cents
class Bundle(Item):
def __init__(self, name, discount=0.0):
self.name, self.discount, self.children = name, discount, []
def add(self, item):
self.children.append(item)
return self
def price(self):
total = sum(child.price() for child in self.children)
return round(total * (1 - self.discount))
ebook = Product("Python Basics", 1500)
starter = Bundle("Starter").add(ebook).add(Product("Testing", 1000))
holiday = Bundle("Holiday", discount=0.2).add(starter).add(Product("Asyncio", 2000))
for item in (ebook, starter, holiday):
print(item.name, item.price())
# Output: Python Basics 1500
# Output: Starter 2500
# Output: Holiday 3600
The loop calls price on a product and on two bundles without knowing which is which, and the holiday bundle applies its discount to the sum of a nested bundle and a product: (2500 + 2000) × 0.8 = 3600. Adding a new kind of item, such as a subscription, requires one new class that implements price, and no change in the bundles or in the client.
Walking the Tree with Generators
Operations that must visit every node, such as listing a file tree, are naturally written as generators: each leaf yields itself, and each composite yields itself and then delegates to its children with yield from, the mechanism described in the article devoted to yield. In Python the common interface may also remain implicit, since any object with the right methods takes part in the tree.
class File:
def __init__(self, name, size):
self.name, self.size = name, size
def total_size(self):
return self.size
def walk(self, prefix=""):
yield prefix + self.name, self.size
class Folder:
def __init__(self, name, *children):
self.name, self.children = name, list(children)
def total_size(self):
return sum(child.total_size() for child in self.children)
def walk(self, prefix=""):
path = prefix + self.name + "/"
yield path, self.total_size()
for child in self.children:
yield from child.walk(path)
root = Folder("project", File("README.md", 2),
Folder("src", File("app.py", 12), File("util.py", 4)))
for path, size in root.walk():
print(path, size)
# Output: project/ 18
# Output: project/README.md 2
# Output: project/src/ 16
# Output: project/src/app.py 12
# Output: project/src/util.py 4
The client receives the nodes one at a time, in depth-first order, and can stop the walk early without visiting the rest of the tree. The example also contains a hidden cost: walk calls total_size on every folder, and each call traverses the whole subtree again, so a deep tree is summed many times, a pitfall examined below.
Transparency or Safety
This section addresses a design decision that the pattern leaves open: where the methods that add and remove children are declared. In the transparent design, the component declares them, so that every node has the same interface, but a leaf must then reject them at run time. In the safe design, only the composite declares them, as in the examples above, so a leaf cannot receive children by mistake, but a client that builds the tree must know which nodes are composites. Python programs usually prefer the safe design, because duck typing already lets the client use leaves and composites uniformly for the operations that matter, such as price or walk.
A Composite in the Standard Library
The xml.etree.ElementTree module follows the transparent design: every Element can hold child elements, has a length, can be iterated over its children and offers iter, which walks its whole subtree. The following example sums the prices of items placed at different depths of a document.
import xml.etree.ElementTree as ET
menu = ET.fromstring(
'<menu><item price="4"/>'
'<group><item price="3"/><item price="5"/></group></menu>'
)
print(len(menu), [child.tag for child in menu]) # Output: 2 ['item', 'group']
print(sum(int(e.get("price")) for e in menu.iter("item"))) # Output: 12
The call menu.iter("item") finds the item at the top level and the two inside the group without any distinction, which is the uniform treatment that the pattern promises. Adding operations to such a tree without editing its classes is the purpose of the Visitor pattern, examined in the article devoted to the Visitor pattern.
Pitfalls of the Composite Pattern
A composite delegates through recursion, so most of its errors concern the shape of the tree and the cost of visiting it. Six pitfalls are distinguished, which are the following:
- Cycles. A folder added, directly or indirectly, to one of its own descendants turns the tree into a graph, and every recursive operation runs until Python raises
RecursionError. - Excessive depth. Even without cycles, a tree deeper than the recursion limit of CPython, 1000 frames by default, cannot be traversed recursively; an explicit stack avoids the limit.
- Repeated aggregation. Recomputing a total on every query traverses the subtree each time; caching it requires invalidating the cache whenever a descendant changes.
- Shared children. The same object placed in two composites is counted twice and changes in both places at once.
- Leaves that pretend to be containers. In the transparent design, a leaf that silently ignores
addhides construction errors; it should raise an exception. - Forcing a tree onto flat data. A list of items with no nesting needs a list, not a composite.
The first pitfall is reproduced in the following example, together with a composite that refuses the child that would close a cycle.
class Folder:
def __init__(self, name):
self.name, self.children = name, []
def add(self, child):
self.children.append(child)
def count(self):
return 1 + sum(child.count() for child in self.children)
a, b = Folder("a"), Folder("b")
a.add(b)
b.add(a)
try:
a.count()
except RecursionError:
print("RecursionError") # Output: RecursionError
class SafeFolder(Folder):
def contains(self, node):
return node is self or any(
isinstance(child, SafeFolder) and child.contains(node)
for child in self.children
)
def add(self, child):
if isinstance(child, SafeFolder) and child.contains(self):
raise ValueError(f"adding {child.name!r} would create a cycle")
super().add(child)
x, y = SafeFolder("x"), SafeFolder("y")
x.add(y)
try:
y.add(x)
except ValueError as error:
print(error) # Output: adding 'x' would create a cycle
The check in add costs one traversal of the new child's subtree, which is paid once, when the tree is built, instead of producing an error later, when it is used. A composite that maintains a reference to its parent can perform the same check by walking upwards, which is cheaper in wide trees.
Choosing a Structure for Nested Data
Consequently, the pattern pays off when the data are genuinely recursive and the client must treat each level in the same way, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Elements and groups nested to any depth | A composite with a common interface |
| A flat collection of elements | A list or a dictionary |
| Visiting every node in order | A generator with yield from |
| Trees deeper than the recursion limit | Iteration with an explicit stack |
| Totals queried often on a tree that rarely changes | A cached aggregate, invalidated on change |
| New operations over a stable tree | The Visitor pattern |
| Hierarchical documents | xml.etree.ElementTree or an equivalent library |
Conclusion
It is concluded that the Composite pattern lets a client treat single elements and nested groups through one interface, so that a question asked of the root is answered by delegation down to every leaf, and that Python supports it naturally through duck typing, generators and modules such as xml.etree.ElementTree. This magic depends on keeping the structure a tree, without cycles or shared children, and on controlling the cost of recursive traversal. Capturing the internal state of an object so that it can be restored later, without exposing that state to other objects, is the purpose of the Memento pattern, which is developed in a future article of this series.