Python Design Patterns

Composite Pattern in Python

Composite represents tree structures while letting clients handle leaves and containers uniformly.

What is Composite Pattern?

Composite represents tree structures while letting clients handle leaves and containers uniformly.

Treat individual objects and object groups through the same interface.

When should you use it?

  • Solve recurring object-design problems with proven structures.
  • Decouple responsibilities so code is easier to extend and test.
  • Use shared design vocabulary when discussing architecture with a team.

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())

Expected output

6

How it works

Number and Sum both implement total, allowing nested groups to be evaluated recursively.

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 Python IDE →