Skip to content
Pyrula

Composition

Three small helpers for putting functions together. Nothing magic, they just read better than nested calls.

pipe threads a value through functions left to right. It replaces h(g(f(x))), which you have to read inside out.

from pyrula import pipe
pipe(
" Hello World ",
str.strip,
str.lower,
lambda s: s.replace(" ", "-"),
) # "hello-world"

flow is pipe without the value: it builds a reusable function out of the steps.

from pyrula import flow
slugify = flow(str.strip, str.lower, lambda s: s.replace(" ", "-"))
slugify(" Hello World ") # "hello-world"

partial fixes some arguments up front and gives back a function waiting for the rest. Handy for dropping a configured function into a pipe or flow.

from pyrula import partial
def clamp(lo, hi, x):
return max(lo, min(hi, x))
clamp_byte = partial(clamp, 0, 255)
clamp_byte(300) # 255

flow is Scala’s f andThen g (or Function.chain); pipe is the pipe from scala.util.chaining (x.pipe(f)); partial is partial application, the same idea as currying a function and fixing its leading arguments.