Builder pattern equivalent in Python

name_masked picture name_masked · Aug 15, 2012 · Viewed 44k times · Source

In Java, you can use the builder pattern to provide a more readable means to instantiating a class with many parameters. In the builder pattern, one constructs a configuration object with methods to set named attributes, and then uses it to construct another object.

What is the equivalent in Python? Is the best way to mimic the same implementation?

Answer

Mechanical snail picture Mechanical snail · Aug 15, 2012

Design patterns can often be replaced with built-in language features.

Your use case

You say "I wanted to have a more readable "means" to instantiating a class with many parameters.". In Java's case:

[A] use case for the builder pattern is when the constructor of the object to be built must take very many parameters. In such cases, it is often more convenient to lump such configuration parameters in a builder object (setMaxTemperature(int t), setMinTemperature(int t), set.. , etc. ) than to burden the caller with a long list of arguments to pass in the class's constructor..

Builder pattern not needed

But Python supports named parameters, so this is not necessary. You can just define a class's constructor:

class SomeClass(object):
    def __init__(self, foo="default foo", bar="default bar", baz="default baz"):
        # do something

and call it using named parameters:

s = SomeClass(bar=1, foo=0)

Note that you can freely reorder and omit arguments, just as with a builder in Java you can omit or reorder calls to the set methods on the builder object.

Also worth stating is that Python's dynamic nature gives you more freedom over construction of objects (using __new__ etc.), which can replace other uses of the builder pattern.

But if you really want to use it

you can use collections.namedtuple as your config object. namedtuple() returns a new type representing a tuple, each of whose parameters has a given name, without having to write a boilerplate class. You can use objects of the resulting type in a similar way to Java builders. (Thanks to Paul McGuire for suggesting this.)

StringBuilder

A related pattern is Java's StringBuilder, which is used to efficiently construct an (immutable) String in stages. In Python, this can be replaced with str.join. For example:

final StringBuilder sb = new StringBuilder();
for(int i = 0; i < 100; i++)
    sb.append("Hello(" + i + ")");
return sb.toString();

can be replaced with

return "".join(f"Hello({i})" for i in range(100))