Function Composition

Concepts covered: functools

Composition builds a new function from 2 existing ones. compose(f, g) returns a function that calls g and hands its result to f, so compose(f, g)(x) equals f(g(x)). The result is an ordinary function object: you can name it, pass it, store it in a dict, or compose it again.

def compose(f, g):
    return lambda x: f(g(x))

def double(likes):
    return likes * 2

def add_bonus(likes):
    return likes + 5

print(compose(double, add_bonus)(10))
print(compose(add_bonus, double)(10))

Output:

30
25

Reading compose(double, add_bonus) left to right names double first, yet add_bonus runs first: 10 becomes 15, then 30. Swapping the arguments gives 25. That right-to-left order follows the math notation f(g(x)), and misreading it is a frequent source of composition bugs.

A pipe reads in the order it runs

For more than 2 steps, a left-to-right pipe is easier to check against the path the data takes. reduce does the work: the accumulator starts as the input value, and each step replaces it with step(accumulator).

from functools import reduce

def pipe(*steps):
    return lambda value: reduce(lambda acc, step: step(acc), steps, value)

def double(likes):
    return likes * 2

def add_bonus(likes):
    return likes + 5

score = pipe(add_bonus, double, str)
print(repr(score(10)))
print(repr(pipe()(10)))

Output:

'30'
10

pipe(add_bonus, double, str) runs in the order written and returns the string '30'. pipe() with no steps returns its input unchanged, because reduce with an initial value and nothing to fold returns that initial value. An empty pipeline is the identity function, so a pipeline built from a configuration list that turns out empty still behaves.

Composing steps that take a stream

Composition stays lazy when every step takes an iterable and returns an iterator. The composed pipeline is then a single function from stream to stream, and nothing runs until a consumer pulls. A step that needs a setting comes from partial; a step that is a single expression comes from a lambda inside map or filter.

from dataclasses import dataclass
from functools import partial, reduce
from itertools import islice

@dataclass(frozen=True)
class Like:
    user: str
    post: str
    account_age_days: int

def pipe(*steps):
    return lambda value: reduce(lambda acc, step: step(acc), steps, value)

def only_new(likes, max_age):
    return filter(lambda like: like.account_age_days <= max_age, likes)

def users(likes):
    return map(lambda like: like.user, likes)

first_new_likers = pipe(
    partial(only_new, max_age=0),
    users,
    lambda names: islice(names, 2),
    list,
)

stream = iter([Like("ana", "p1", 1), Like("cy", "p1", 0),
               Like("bo", "p2", 400), Like("dee", "p2", 0),
               Like("eli", "p3", 0)])
print(first_new_likers(stream))
print(next(stream))

Output:

['cy', 'dee']
Like(user='eli', post='p3', account_age_days=0)
list pulls; each request travels back to the stream and a single Like moves forward, until islice holds 2 names
  • like stream (source, iterator of Like)
  • only_new (transform, filter, max_age=0)
  • users (transform, map)
  • first 2 (transform, itertools.islice)
  • list (consumer, collects the names)
  • like stream -> only_new
  • only_new -> users
  • users -> first 2
  • first 2 -> list

The pipeline printed 2 names, and next(stream) then returned eli's record, so the run pulled exactly 4 events: ana and bo were read and rejected, cy and dee passed. partial(only_new, max_age=0) fixed the setting and left a 1-argument step. The lambda adapts islice, whose count is a second positional argument that partial cannot fill on its own.

Rules that keep composed steps safe

Do
  • Give each step a single input and a single output, so any 2 steps can be joined
  • Pass frozen records between steps so no step can edit another's data
  • Make stream steps take an iterable and return an iterator
  • Name a composed pipeline after what it produces, as with first_new_likers
  • Test each step alone on a 3-item list before composing
Avoid
  • Mix compose order and pipe order in the same codebase
  • Let a step print, write or mutate as a side effect
  • Hand the same iterator to 2 steps
  • Put list() mid-stream unless a step needs every item at once
  • Hide a 5-line step inside a lambda

What does this program print?

from functools import reduce

def pipe(*steps):
    return lambda value: reduce(lambda acc, step: step(acc), steps, value)

trim = pipe(str.strip, str.lower, lambda s: s[:3])
print(trim("  INSTAGRAM "))

About this lesson

This section is part of the Functional Programming: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.