Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Builder pattern equivalent in Python

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?

like image 945
name_masked Avatar asked Aug 15 '12 21:08

name_masked


People also ask

Is builder pattern used in Python?

Usage of the pattern in Python Usage examples: The Builder pattern is a well-known pattern in Python world. It's especially useful when you need to create an object with lots of possible configuration options.

Is builder pattern same as factory?

A Factory Design Pattern is used when the entire object can be easily created and object is not very complex. Whereas Builder Pattern is used when the construction process of a complete object is very complex.

What is __ new __ in Python?

The __new__() is a static method of the object class. It has the following signature: object.__new__(class, *args, **kwargs) Code language: Python (python) The first argument of the __new__ method is the class of the new object that you want to create.

Does StringBuilder use builder pattern?

Analyzing documentation, I can say that StringBuilder does not use corresponding pattern. It use Composite pattern. Builder pattern does not gather object "manually by your hands step-by-step" or in loop. It has ready-made solutions.


1 Answers

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)) 
like image 100
Mechanical snail Avatar answered Oct 11 '22 08:10

Mechanical snail