Does Python Need the Builder Pattern? Constructing Complex Objects Step by Step

This article explains when the Builder pattern is useful in Python, how a builder that validates in build() and returns new immutable objects differs from the naive version, and why keyword arguments and data classes often suffice.

A bright green snake with pale markings coiled in neat, overlapping loops on a dark branch against a deep green background
Photo by Jake Bond on Unsplash

A class with many attributes, several of them optional, tends to acquire a constructor whose calls are hard to read: a sequence of positional values in which a lone True says nothing about the option it enables. The present article addresses the Builder pattern, which assembles such an object step by step through a separate builder and creates it only when every part has been supplied. It first shows that Python already removes most of the problem with keyword arguments and data classes, then develops a builder that validates the combination of parts and produces a new immutable object on each call, and finally analyses the errors of the naive version found in many tutorials. Separating how an object is assembled from the object that results, so that construction can be validated, repeated and encoded as a recipe, is the secret weapon of the Builder pattern.

Keyword Arguments Before a Builder

The pattern was described for languages in which a constructor accepts only positional arguments, so that every optional part requires either another constructor or an explicit None. Python does not share that limitation: keyword-only parameters with defaults make every call self-describing, and a frozen data class declared with kw_only=True generates such a constructor automatically, as described in the article devoted to keyword-only parameters. Validation of the combination of fields fits in __post_init__, and dataclasses.replace produces variants without repeating the unchanged fields.

from dataclasses import dataclass, replace

@dataclass(frozen=True, kw_only=True)
class Computer:
    cpu: str
    ram_gb: int = 16
    gpu: str | None = None
    rgb: bool = False

    def __post_init__(self):
        if self.rgb and self.gpu is None:
            raise ValueError("RGB lighting requires a GPU")

office = Computer(cpu="Ryzen 5")
gaming = replace(office, gpu="RTX 4080", ram_gb=64, rgb=True)
print(office)  # Output: Computer(cpu='Ryzen 5', ram_gb=16, gpu=None, rgb=False)
print(gaming.gpu, gaming.ram_gb)  # Output: RTX 4080 64

Every argument is named, the optional parts are simply omitted, and an inconsistent combination is rejected at creation. For most classes this is sufficient, and the data classes described in the article devoted to data classes are the idiomatic first choice. A builder becomes useful when the parts arrive at different moments, for example while a file or a request is parsed, when the steps must follow an order, or when the same sequence of steps must produce several objects.

A Builder That Accumulates and Validates

A sound builder stores the parts it receives, returns itself from each step so that the calls can be chained, and creates the product only in build, where the whole combination is checked. Because the product is created anew on each call and is immutable, a builder can be reused, and products built earlier are never affected by later steps.

from dataclasses import dataclass

@dataclass(frozen=True)
class Computer:
    cpu: str
    ram_gb: int
    gpu: str | None

class ComputerBuilder:
    def __init__(self):
        self._parts = {"ram_gb": 16, "gpu": None}

    def cpu(self, model):
        self._parts["cpu"] = model
        return self

    def ram(self, gigabytes):
        self._parts["ram_gb"] = gigabytes
        return self

    def gpu(self, model):
        self._parts["gpu"] = model
        return self

    def build(self):
        if "cpu" not in self._parts:
            raise ValueError("a CPU is required")
        return Computer(**self._parts)

builder = ComputerBuilder().cpu("Ryzen 9").ram(32)
first = builder.build()
second = builder.gpu("RTX 4080").build()
print(first.gpu, second.gpu, first is second)  # Output: None RTX 4080 False
try:
    ComputerBuilder().ram(8).build()
except ValueError as error:
    print(error)  # Output: a CPU is required

The first product keeps no graphics card even though the builder received one afterwards, because each call to build creates a separate frozen object. The missing processor is detected in build, the single place where the combination is complete, rather than in every step.

Build Orders: Directors That Encode a Recipe

Strategy games reward the memorized build order, a fixed sequence of constructions that a player repeats at the start of every match. This means that the director of the pattern is a function or object that calls the builder's steps in a known order, so that a configuration is defined once and reproduced on demand. The analogy, however, stops at this point, because a player adapts the order to the opponent, whereas a director repeats exactly the same steps, and every variation requires another director or a parameter. In Python a director is usually an ordinary function that receives a builder, which lets the same recipe work with any builder that offers the same steps, while the choice of which class to build remains the concern examined in the article devoted to the Factory pattern. The standard library applies the same idea to text: a list of fragments joined once with str.join, or an io.StringIO written piece by piece and read with getvalue, assembles a string step by step and produces it at the end.

Pitfalls of the Builder Pattern

A builder adds a second class for every product, so its errors come either from implementing it carelessly or from introducing it where a constructor suffices. Six pitfalls are distinguished, which are the following:

  1. A shared, mutable product. A builder that creates the product in its own __init__ and returns it from build hands the same object to every caller, and later steps modify products that were already delivered.
  2. No validation at build. Checking each step in isolation cannot detect an invalid combination, such as lighting without a graphics card.
  3. Builders for simple classes. Keyword arguments, defaults and data classes already make most constructors readable.
  4. Duplicated fields. The builder repeats every field of the product, so both must change together; generating the product with a data class reduces the duplication.
  5. Chains that hide errors. A long fluent chain reports an exception on a single line, which makes the failing step harder to locate.
  6. Builders that outlive their purpose. A builder kept as a long-lived object accumulates state from unrelated constructions.

The first pitfall, typical of the naive version, is reproduced in the following example.

class Computer:
    def __init__(self):
        self.gpu = None

class NaiveBuilder:
    def __init__(self):
        self.computer = Computer()

    def gpu(self, model):
        self.computer.gpu = model
        return self

    def build(self):
        return self.computer

builder = NaiveBuilder()
office = builder.build()
gaming = builder.gpu("RTX 4080").build()
print(office is gaming, office.gpu)  # Output: True RTX 4080

The office computer, built first and expected to have no graphics card, received one when the builder was used again, because both names refer to the same mutable object. Creating the product inside build, as in the previous section, and making it immutable removes the error.

Choosing How to Construct an Object

Consequently, the Builder pattern is justified only when construction is gradual, ordered or repeated, as the following table summarizes.

Situation Recommended approach
Few fields, some optional Keyword arguments with defaults
Many fields, validation of combinations Frozen data class with kw_only=True and __post_init__
Variants of an existing object dataclasses.replace
Parts that arrive gradually, for example while parsing A builder that validates in build
The same configuration reproduced many times A director function that drives a builder
Choosing which class to instantiate A factory
Assembling a long string from fragments str.join or io.StringIO

Conclusion

It is concluded that the Builder pattern separates the assembly of a complex object from the object itself, that a sound builder accumulates parts, validates their combination in build and returns a new immutable product on each call, and that in Python keyword arguments and data classes cover most of the cases that motivate the pattern elsewhere. This magic fails when the builder shares a mutable product with its callers, so the product must be created at the end and never modified afterwards. Deciding whether to check a condition before acting or to attempt the action and handle the exception is the subject of the EAFP and LBYL styles, which are developed in a future article of this series.