97

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?

13
  • 7
    As a rule of thumb, transplanting an implementation from Java to Python will usually result in un-idiomatic code. And vice versa. Why do you ask? Commented Aug 15, 2012 at 21:07
  • 6
    @delnan: Well, I wanted to have a more readable "means" to instantiating a class with many parameters. Hence the question Commented Aug 15, 2012 at 21:13
  • 2
    @delnan: Isn't asking for a Builder class implementation mean exactly what I wrote in comments !! (and that is not a question). Also, reading up the XY trap article, I doubt this question is applicable. I have posted a more broader question instead of specifying my implementation (attempted solution) or issue specific to any example. Commented Aug 15, 2012 at 21:23
  • 1
    For classes that are essentially immutable structs, use namedtuple (imported from collections). Commented Aug 15, 2012 at 21:26
  • 3
    @delnan: So you would like that I should explicitly mention "how to construct an object" in my article? If that's the case, I am sorry but I see no intent to make the change (no disrespect please). Anybody with a clear knowledge of Builder pattern in Java would know what the question means. You can refer to: stackoverflow.com/questions/328496/… to update yourself with the key feature of Builder pattern i.e. building an object with many parameters. Commented Aug 15, 2012 at 21:35

7 Answers 7

144

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))
Sign up to request clarification or add additional context in comments.

5 Comments

+1 for an answer that is likely to help others in the future.
@mechanical-snail This may just be my inexperience speaking, but how do I use those "easy, pythonic, don't-need-no-builders" solutions for something like a StringBuilder, whose methods can be invoked multiple times, order being important, before returning the finished immutable product?
Yah, I agree. I found this answer while looking for one of those complicated builders.
@kaay: There's "".join(iterable). Example in edit.
As a note, building up a list (or other data structure - often with list comprehensions or generators), and then passing the iterable into your constructor is the preferred way of doing any kind of equivalent to a builder that has that kind of behaviour.
64

The OP set themselves up for a fall by casting the Builder pattern as Java specific. It's not. It's in the Gang of Four's book and is potentially relevant to any object oriented language.

Unfortunately, even the Wikipedia article on the Builder pattern doesn't give it enough credit. It's not simply useful for code elegance. Builder patterns are a great way to create immutable objects that need to be mutable until they're used. Immutable state is especially critical in functional paradigms, making the Builder an excellent object-oriented pattern for python.

I've provided an an example Builder + ImmutableObject implementation below using the collections.namedtuple, borrowed and modified from "How to make an immutable object in python". I've kept the Builder fairly simple. However, setter functions could be provided that return the Builder itself to allow call chaining. Or @property syntax could be used in the Builder to provide attribute setters that check attribute validity prior to setting.

from collections import namedtuple

IMMUTABLE_OBJECT_FIELDS = ['required_function_result', 'required_parameter', 'default_parameter']

class ImmutableObjectBuilder(object):
    def __init__(self, required_function, required_parameter, default_parameter="foo"):
        self.required_function = required_function
        self.required_parameter = required_parameter
        self.default_parameter = default_parameter

    def build(self):
        return ImmutableObject(self.required_function(self.required_parameter),
                               self.required_parameter,
                               self.default_parameter)

class ImmutableObject(namedtuple('ImmutableObject', IMMUTABLE_OBJECT_FIELDS)):
    __slots__ = ()

    @property
    def foo_property(self):
        return self.required_function_result + self.required_parameter

    def foo_function(self):
        return self.required_function_result - self.required_parameter

    def __str__(self):
        return str(self.__dict__)

Example usage:

my_builder = ImmutableObjectBuilder(lambda x: x+1, 2)
obj1 = my_builder.build()
my_builder.default_parameter = "bar"
my_builder.required_parameter = 1
obj2 = my_builder.build()
my_builder.required_function = lambda x: x-1
obj3 = my_builder.build()

print obj1
# prints "OrderedDict([('required_function_result', 3), ('required_parameter', 2), ('default_parameter', 'foo')])"
print obj1.required_function_result
# prints 3
print obj1.foo_property
# prints 5
print obj1.foo_function()
# prints 1
print obj2
# prints "OrderedDict([('required_function_result', 2), ('required_parameter', 1), ('default_parameter', 'bar')])"
print obj3
# prints "OrderedDict([('required_function_result', 0), ('required_parameter', 1), ('default_parameter', 'bar')])"

In this example, I created three ImmutableObjects, all with different parameters. I've given the caller the ability to copy, modify, and pass around a mutable configuration in the form of the builder while still guaranteeing immutability of the built objects. Setting and deleting attributes on the ImmutableObjects will raise errors.

Bottom line: Builders are a great way to pass around something with mutable state that provides an object with immutable state when you're ready to use it. Or, stated differently, Builders are a great way to provide attribute setters while still ensuring immutable state. This is especially valuable in functional paradigms.

4 Comments

Yes, immutable objects don't really exist in Python (actually, they don't exist in Java either: you can always grab onto private members and change them via reflection). But at least the convention lets you know that you should expect Bad Things(TM) if you do change the state. Regarding the setter syntax: it's less pythonic, but more consistent with the formal Builder pattern. By returning the builder, you get call-chaining (callers don't have to keep typing my_builder.), which becomes convenient when you have many parameters to set. I think either style is reasonable.
I modified the implementation to an actually immutable object (using tuple). I simplified the Builder while pointing out other options available for implementing the Builder. My original implementation muddied the point: Builders are a nice way to work with something mutable that turns into something immutable. Hopefully this implementation is more clear and clean.
For everyone discounting the value of a builder in Python... look into the best examples before assuming from other answer & comments that the builder pattern is just Java fluff. It isn't about Java. The builder pattern is about separating (1) the complex construction of an object which usually includes enforcing constraints from (2) the later usage of the object. This way the object you want to build isn't later polluted with the methods needed to build. Also, the resulting object doesn't have to be immutable.
In response to the older comments saying Python doesn't involve a lot of immutable objects, it might be worth pointing out that nowadays, defining immutable types with @dataclass(frozen=True) (introduced in Python 3.7, which was released in 2018) is idiomatic and commonplace.
36

I disagree with @MechanicalSnail. I think a builder implementation similar to one referenced by the poster is still very useful in some cases. Named parameters will only allow you to simply set member variables. If you want to do something slightly more complicated, you're out of luck. In my example I use the classic builder pattern to create an array.

class Row_Builder(object):
  def __init__(self):
    self.row = ['' for i in range(170)]

  def with_fy(self, fiscal_year):
    self.row[FISCAL_YEAR] = fiscal_year
    return self

  def with_id(self, batch_id):
    self.row[BATCH_ID] = batch_id
    return self

  def build(self):
    return self.row

Using it:

row_FY13_888 = Row_Builder().with_fy('FY13').with_id('888').build()

1 Comment

This is long past, but for future people reading this - the arguments are actually passed to __init__ which is the initializer, not the constructor. The constructor in python is the magic classmethod __new__, which you much less commonly customize. In any case, yes a builder can be helpful and I am mostly commenting on semantics.
18

I have just come across the need for building this pattern and stumbled across this question. I realize how old this question is but might as well add my version of the builder pattern in case it is useful to other people.

I believe using a decorator to specify builder classes is the most ergonomic way to implement the builder pattern in python.

def buildermethod(func):
  def wrapper(self, *args, **kwargs):
    func(self, *args, **kwargs)
    return self
  return wrapper

class A:
  def __init__(self):
    self.x = 0
    self.y = 0

  @buildermethod
  def set_x(self, x):
    self.x = x

  @buildermethod
  def set_y(self, y):
    self.y = y

a = A().set_x(1).set_y(2)

2 Comments

You could also just have written return self at the end of each function block, and you'd end up with less lines of code, you don't gain much from a decorator whose sole purpose is to do one single, simple thing. Additionally, it's unconventional for a set method to have anything but a None return type, so your code is not very intuitive at all
I think this is better than just doing return self at the end of each function block. Lines of code are roughly the same, but the annotation is more helpful because it makes it stand out that this is a builder method, and will have the appropriate behavior.
7

builder and constructor are not the same thing, builder is a concept, constructor is a programming syntax. There is no point to compare the two.

So sure you can implement the builder pattern with a constructor, a class method or a specialized class, there is no conflict, use whichever one suit your case.

Conceptually, builder pattern decouple the building process from the final object. Take a real world example of building a house. A builder may use a lot of tools and materials to build a house, but the final house need not have those tools and excess materials lying around after it is build.

Example:

woodboards = Stores.buy(100)
bricks = Stores.buy(200)
drills = BuilderOffice.borrow(4)

house = HouseBuilder.drills(drills).woodboards(woodboards).bricks(bricks).build()

Comments

7

Just implement the Builder pattern by adding a Method chaining, and in most cases I get easy-reading code like that:

pizza = (
  PizzaBuilder("Margherita")
  # add ingredients
  .set_dough("cross")
  .set_sauce("tomato")
  .set_topping("mozzarella")
  # cook
 .build()
)

To do this, I use the following template:

from abc import ABC, abstractmethod
from dataclasses import dataclass


@dataclass
class Pizza:
    name: str
    dough: str
    sauce: str
    topping: str


class BasePizzaBuilder(ABC):

    @abstractmethod
    def set_dough(self, dough: str) -> Any:
        raise NotImplementedError()

    @abstractmethod
    def set_sauce(self, sauce: str) -> Any:
        raise NotImplementedError()

    @abstractmethod
    def set_topping(self, topping: str) -> Any:
        raise NotImplementedError()


class PizzaBuilder(BasePizzaBuilder):

    def __init__(self, pizza_name: str) -> None:
        self.pizza_name = pizza_name

    def set_dough(self, dough: str) -> BasePizzaBuilder:
        """Set dough."""
        self._dough = dough
        return self
    
    def set_sauce(self, sauce: str) -> BasePizzaBuilder:
        """Set sauce."""
        self._sauce = sauce
        return self
    
    def set_topping(self, topping: str) -> BasePizzaBuilder:
        """Set topping."""
        self._topping = topping
        return self
    
    def build(self) -> Pizza:
        """Cook pizza."""
        return Pizza(
            name=self.pizza_name, 
            dough=self._dough, 
            sauce=self._sauce, 
            topping=self._topping
        )

3 Comments

Simple, readable, comprehensive. Thank you.
Alternatively, due to the dataclass decorator, one can just write pizza = Pizza(name="Margherita", dough="cross", sauce="tomato", topping="mozzarella") which is just as easy to read.
1. That is not a Builder pattern (and original question about that) 2. Why is it "easier to read"? What does it look like when an object contains 10 fields (the usual thing)?
4

The builder pattern in Java can easily be achieved in python by using a variant of:

MyClass(self, required=True, someNumber=<default>, *args, **kwargs)

where required and someNumber are an example to show required params with a default value and then reading for variable arguments while handling the case where there might be None

In case you have not used variable arguments before, refer this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.