Composite Pattern in Python
Treat a single item and a whole group the same way, such as a file and a folder that both report their size.
- Leaves and containers
- A shared interface such as size()
- Recursive totals over a tree
Sum= 6Number(1)Sum= 5Number(2)Number(3)
Groups and items answer the same call
The problem
Folders contain files and other folders; a menu contains items and submenus; an expression contains numbers and smaller expressions. Code that must constantly check "is this a single item or a group?" becomes messy. Composite lets both answer the same call.
Think of it like this
The Composite pattern is like asking for the total weight of a parcel. A single item knows its own weight. A box asks every item inside it, including smaller boxes, and adds up the answers. You ask the outer box the same question you would ask a single item.
Number(1)📦 A single item: knows its own weightSum(...)🗃️ A box holding items and smaller boxessum(child.total() for child in self.children)➕ The box asks each child and adds upexpression.total()⚖️ One question for the whole parcel: 6The Composite pattern treats single objects and groups of objects through the same interface, so a tree of them can be used as one object.
Key points
Number.total()returns its own value: it is a leaf.Sum.total()callstotal()on every child and adds the results.- A child of
Sumcan be anotherSum, which makes the structure a tree. expression.total()returns 6 without the caller checking what kind of object each part is.
When should you use it?
- Tree structures: folders and files, menus and submenus, organization charts.
- Expressions and documents built from nested parts.
- Applying one operation to a whole hierarchy.
When not to use it
- Flat collections without nesting: a simple list is enough.
- Leaves and groups need very different operations: forcing one interface on them adds awkward methods.
Example code
class Number:
# Composite: leaves and containers expose the same operation.
def __init__(self, value): self.value = value
def total(self): return self.value
class Sum:
def __init__(self, *children): self.children = children
def total(self):
# Treat leaves and nested groups uniformly.
return sum(child.total() for child in self.children)
expression = Sum(Number(1), Sum(Number(2), Number(3)))
print(expression.total())
Result of running the code
6
Code explanation
Number and Sum both have a total() method. A Number returns its own value, while a Sum asks each of its children for their total and adds them up. Because a Sum can contain other Sums, Sum(Number(1), Sum(Number(2), Number(3))) computes 1 + (2 + 3) = 6 through the same call.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Checking types instead of using the shared method
isinstance checks break when a new kind of node is added.
if isinstance(child, Number):
total += child.value
total += child.total()
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges