Builder pattern equivalent in Python

Viewed 54712

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?

6 Answers

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)

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