How is this Python design pattern called?

390 views Asked by At

In the ffmpeg-python docs, they used following design pattern for their examples:

(
    ffmpeg
    .input('dummy.mp4')
    .filter('fps', fps=25, round='up')
    .output('dummy2.mp4')
    .run()
)

How is this design pattern called, where can I find more information about it, and what are the pros and cons of it ?

2

There are 2 answers

0
Reznik On BEST ANSWER

This design pattern called builder, you can read about it in here

basically, all the command (except run) change the object, and return it self, which allow you to "build" the object as it go on.

in my opinion is very usefull things, in query building is super good, and can be simplify a code.

think about db query you want to build, lets say we use sql.

# lets say we implement a builder called query

class query:
    def __init__():
        ...
    def from(self, db_name):
        self.db_name = db_name
        return self
    ....
 
q = query()
    .from("db_name") # Notice every line change something (like here change query.db_name to "db_name"
    .fields("username")
    .where(id=2)
    .execute() # this line will run the query on the server and return the output
0
jarmod On

This is called 'method chaining' or 'function chaining'. You can chain method calls together because each method call returns the underlying object itself (represented by self in Python, or this in other languages).

It's a technique used in the Gang of Four builder design pattern where you construct an initial object and then chain additional property setters, for example: car().withColor('red').withDoors(2).withSunroof().

Here's an example:

class Arithmetic:
    def __init__(self):
        self.value = 0

    def total(self, *args):
        self.value = sum(args)
        return self

    def double(self):
        self.value *= 2
        return self

    def add(self, x):
        self.value += x
        return self

    def subtract(self, x):
        self.value -= x
        return self

    def __str__(self):
        return f"{self.value}"


a = Arithmetic().total(1, 2, 3)
print(a)  # 6

a = Arithmetic().total(1, 2, 3).double()
print(a)  # 12

a = Arithmetic().total(1, 2, 3).double().subtract(3)
print(a)  # 9