Python Design Patterns

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.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • Leaves and containers
  • A shared interface such as size()
  • Recursive totals over a tree
Sum(Number(1), Sum(Number(2), Number(3))).total()
  • Sum= 6
    • Number(1)
    • Sum= 5
      • Number(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.

From boxes in boxes to code
Number(1)📦 A single item: knows its own weight
Sum(...)🗃️ A box holding items and smaller boxes
sum(child.total() for child in self.children)➕ The box asks each child and adds up
expression.total()⚖️ One question for the whole parcel: 6
Leaves and groups answer the same call.
In one sentence

The 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

  1. Number.total() returns its own value: it is a leaf.
  2. Sum.total() calls total() on every child and adds the results.
  3. A child of Sum can be another Sum, which makes the structure a tree.
  4. 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

Run code →
main.py
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())
Get a Run button for this example

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.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Checking types instead of using the shared method

isinstance checks break when a new kind of node is added.

Problem
if isinstance(child, Number):
    total += child.value
Fix
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