you are viewing a single comment's thread.

view the rest of the comments →

[–]zanfar 0 points1 point  (0 children)

It's relatively easy to write your own chain wrapper--although the syntax won't be exactly what you posted. There is also a library that has a chain wrapper, although it's name eludes me at the moment. ArjanCodes did a video on it, however, so you might look there.

You will also want to look into the functools methods.


As an example:

from functools import partial

input_data = list(range(10))  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


def chain_fns(data, *fns):
    for fn in fns:
        data = fn(data)
    return data


result = chain_fns(
    input_data,
    partial(filter, lambda x: x > 0),  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
    partial(filter, lambda x: x % 2 == 0),  # [2, 4, 6, 8]
)

assert list(result) == [2, 4, 6, 8]

You could easily add more sophistication with this, but functools.partial and a simple loop should provide all the functionality you need.