Pipe functions in Python

David James Knight
03 Jun 2019

A pipe function passes an object through a sequence of operations, with the output of each operation being the input of the next. Operations are executed in the order written, making pipes more readable than nested functions (which are executed from the inside out).

Code

from functools import reduce

def pipe(obj, *fns):
    return reduce(lambda x, y: y(x), [obj] + list(fns))

Usage example

bill = ["$4.50", "$32.00", "3.90"]
tip = pipe(
    map(lambda x: float(x.replace("$", "")), bill),
    sum,
    lambda x: round(x * .2, 2),
    lambda x: "$" + str(x)
)
print(tip)
# Returns '$8.08'

Compare to a nested function

tip = "$" + str(round(sum(map(lambda x: float(x.replace("$", "")), bill)) * .2, 2))
print(tip)
# Returns '$8.08'

A safe .pipe() method using ES6 Symbols

Use an ES6 Symbol to invoke a pipe function without the potential conflicts caused by monkeypatching a custom method onto the Object prototype.

More >>