To use, import at least
from functional_pipeline import pipeline
pipeline takes 2 arguments,
value is the starting value of the pipeline. This is what gets passed in to the first function in operations.
operations is a List of either functions or tuples.
Pipeline passes the value from one operation to the next. When all of the operations are complete, the result is returned.
The main use of pipelines is to simplify code and reduce unnessiary variables in long chained operations.
def add_1(x): return x + 1 def multiply_2(x): return x * 2 def divide_3(x): return x / 3 def subtract_1(x): return x - 1 start = 5 first = add_1(start) second = mulitply_2(first) third = divide_3(second) final = subtract_1(third)
In this simple example, 3 variables are created, used once, then never again. They often arent needed. One might rewrite this example as
start = 5 final = subtact_1(divide_3(multiply_2(add_1(start))))
This refactored code gets rid of the unused variables, but it becomes harder to read. The order of operations becomes nested, which means you have to read backwards to get the innermost action first. Pipelines fix both of these problems
final = pipeline( start, [ add_1, multiply_2, divide_3, substract_1 ] )
The order of operations is very clear and there is no messy unused variables.
Pipelines also allow you to clear up the one off functions in this case.
Instead of defining all of these single use named functions, we can use
tuple operation paired with the base
from operator import add, mul, truediv, sub from functional_pipeline import pipeline start = 5 final = pipeline( start, [ (add, 1), (mul, 2), (truediv, 3), (sub, 1), ] )
By changing from functions to tuples in the operations list, we allowed for partial application of functions.