🤖📘🍻 Hooray! After 3 years of work, we've finally released a new ebook on design patterns! Check it out »

Composite Design Pattern in Python

Compose objects into tree structures to represent part-whole
hierarchies. Composite lets clients treat individual objects and
compositions of objects uniformly.

import abc

class Component(metaclass=abc.ABCMeta):
    Declare the interface for objects in the composition.
    Implement default behavior for the interface common to all classes,
    as appropriate.
    Declare an interface for accessing and managing its child
    Define an interface for accessing a component's parent in the
    recursive structure, and implement it if that's appropriate

    def operation(self):

class Composite(Component):
    Define behavior for components having children.
    Store child components.
    Implement child-related operations in the Component interface.

    def __init__(self):
        self._children = set()

    def operation(self):
        for child in self._children:

    def add(self, component):

    def remove(self, component):

class Leaf(Component):
    Represent leaf objects in the composition. A leaf has no children.
    Define behavior for primitive objects in the composition.

    def operation(self):

def main():
    leaf = Leaf()
    composite = Composite()

if __name__ == "__main__":

Code examples

More info, diagrams and examples of the Composite design pattern you can find on our new resource Refactoring.Guru.