Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Background: from toolz to pipekit

Where pipekit comes from, and why its operators are classes.

pipekit is toolz with each function replaced by a typed class. This page shows what that inheritance gives, the six things plain functions cannot carry, and why operators settled on a concrete base class while the data flowing through them did not. It is background: for what ships and when to reach for it, read the tour of the core.

Why this page exists

The pipekit design makes more sense once you have seen three things: what it inherited from toolz, what that inheritance cannot do, and why moving from “any function” to a typed operator class is the right call rather than over-engineering. This is the motivation layer; the operators themselves are in the tour of the core.

toolz as the ancestor

pytoolz/toolz is pipekit’s explicit intellectual ancestor. Looking at it directly is the fastest way to see which idea pipekit carries forward and what it adds. Its functional core is a dozen primitives.

The toolz.functoolz surface

The functoolz primitives pipekit inherits from.

toolz primitiveWhat it does
identity(x)pass the value through unchanged
pipe(value, *funcs)apply functions left to right to a value
compose(*funcs)right-to-left composition: f(g(h(x)))
compose_left(*funcs)left-to-right composition
juxt(*funcs)several outputs: juxt(f, g)(x) is (f(x), g(x))
do(f, x)run f(x) for its side effect and return x
complement(pred)negate a predicate
excepts(exceptions, func, handler)catch the listed exceptions while applying func
memoize(func)cache results by input
currypartial application, as a class wrapper
thread_first, thread_lastClojure-style threading macros
flip(f, a, b)call f(b, a)

toolz also ships itertoolz (about 30 functions on iterables) and dicttoolz (about 15 on dicts). pipekit inherited from functoolz first. Since pipekit-ops 0.2.1 it also has operator counterparts of the dicttoolz and itertoolz functions that pipelines reach for (in pipekit_ops.operators), so reshaping a dict or filtering a list no longer needs a Lambda.

The mental model

toolz says a pipeline is a sequence of pure functions, composed with pipe or compose. Each function is responsible for its transform and nothing else; metadata, types and side effects are someone else’s problem.

from toolz import pipe
from toolz.curried import do

pipe(
    "  HELLO  ",
    str.strip,
    str.lower,
    do(print),  # side effect: prints "hello"
    lambda s: s.split("l"),
)
# → ['he', '', 'o']

This is functional composition over plain Python. Functions are values, composition is an operation, and side effects are explicit (do). It is elegant and minimal, and it directly inspired pipekit’s | syntax, the Sequential shape, the Tap / Sink split, and the juxt / Fanout pair.

One-to-one mappings to pipekit

Almost every pipekit primitive has a toolz ancestor. The mapping is tight enough that the most accurate one-line description of pipekit is toolz, with each function replaced by a typed class.

toolz primitives and their pipekit counterparts.

toolzpipekitWhat pipekit’s version adds
pipe(value, *funcs)pipe(value, *operators), Sequential(operators)(value)operators carry config; a readable repr; reuse
compose_left(*funcs)compose_left(...), op1 | op2 | op3| flattens into one Sequential; class-typed steps
compose(*funcs)compose(...)the same, in mathematical order
do(f, x)Tap(fn), Sink(write_fn)the closure is owned by an operator with a name; marked forbid_in_yaml
juxt(f, g, h)juxt(...) (tuple) and Fanout({...}) (dict)both shapes; named outputs for downstream steps
memoizeCache, with Memoize as an aliasconfig-aware hashing; a named Store (a DirectoryStore) keeps entries across restarts and processes
exceptsTry, Coalesceoperator-shaped arms; an explicit exception list
complementcomplementships as a plain function
identityIdentityan operator, so it composes everywhere
curryimplicit in __init__an operator’s constructor is its partial application
map (Python’s, or an Executor.map)Map(op, executor=...)one engine for serial, thread, process and async runs, with a bounded window
sandbox.foldFoldan associative tree fold over chunks, parallel through Map
get, get_in, merge, assoc, dissoc, update_in, valmapGet, GetIn, Merge, Assoc, Dissoc, UpdateIn, ValMap (plus Pick, Rename)they round-trip through dumps / loads; none mutates its input
filter, remove, reduce (from functools), partition_all, concat, groupby, countby, unique, takeFilter, Remove, Reduce, PartitionAll, Concat, GroupBy, CountBy, Unique, Take (plus Not, Zip, Count, SortBy)predicates and keys are operators or plain keys, so the pipeline stays serialisable

The same pipeline in both libraries shows the difference. Both outputs below are from real runs.

toolz
pipekit
from toolz import compose_left

steps = compose_left(str.strip, str.lower, lambda s: s.split("l"))
print(steps)
# Compose(<function <lambda> at 0x7f…>, <method 'lower' of 'str' objects>,
#         <method 'strip' of 'str' objects>)

toolz is the design template. pipekit is the typed, introspectable, serialisable variant of the same idea.

Where toolz stops being enough

toolz handles the mechanics of function composition cleanly. Six things are beyond it, and each is why the domain libraries needed more.

The six gaps, and where pipekit puts each one.

GapWhat toolz givesWhere it lives in pipekitStatus
Introspectiona repr of raw function objectsnamed operators, Sequential.__getitem__, summary()ships
Serialisationnothingget_config, dumps / loads, from_stateships, nested pipelines included; closure-holding operators excluded
Dual-mode dispatcheager calls onlyOperator.__call__ switches on Node inputsships
Control flowPython if / match outside the pipelineBranch, Switch, Try, Coalesceships
Shape trackingAny → AnySignature, Sequential.summary()ships; needs signatures
Closure disciplineany closure, silentlythe forbid_in_yaml class flagships

Introspection

A toolz composition is not opaque: Compose prints its steps (the toolz tab above). But it prints them as raw function objects, in reverse order, with lambdas anonymous and no configuration or per-step state to inspect. That is fine at an interactive prompt. For a 14-step preprocessing pipeline that has to be audited, you want named steps, in order, that you can index (steps[2]) and summarise.

Serialisation

toolz pipelines are tuples of function references and closures. They do not round-trip to YAML, JSON or a Hydra config, and they cannot be shipped to a worker process and rebuilt. Every deployment shape in the patterns (an ETL job, a web service, a tile server, a regulatory artifact, an orchestrator) needs serialisation in some form.

pipekit gives every operator a get_config(), and a pipeline’s state is its whole configuration: each nested operator as its own record, and for a Graph every node and its wiring. That record round-trips through JSON, and through _target_ YAML with pipekit-experiment’s HydraConfigLoader:

import pipekit_ops as pk
from pipekit_ops import Cache, Const, Identity, Sequential

pipe = Cache(Sequential([Const(3), Identity()]))
back = pk.loads(pk.dumps(pipe))
back.state == pipe.state  # → True
pk.pipeline_hash(back) == pk.pipeline_hash(pipe)  # → True

Only operators that hold a closure (Lambda, Tap, a Branch predicate) stay out: they are flagged forbid_in_yaml, and loads refuses them wherever they sit in the tree.

Dual-mode dispatch

toolz functions only run eagerly. You cannot pass a symbolic placeholder through them to build a graph that runs later. Graph building (the Input / Node API) needs the same callable to behave differently depending on whether its argument is data or a placeholder. In pipekit that switch lives once, in Operator.__call__: any Node argument builds a graph node, and anything else calls _apply.

Control flow

In a toolz-style pipeline, a conditional is a Python if or match outside the pipeline, which splits the pipeline apart wherever one is needed. pipekit makes conditionals first-class operators (Branch, Switch, Try, Coalesce), composable inside a Sequential like any other step.

Shape tracking

Every toolz step is Any → Any. For scientific data that hides structure worth surfacing: named dimensions, units, a coordinate system. pipekit’s Signature lets an operator declare what it accepts and returns, and Sequential.summary() prints a Keras-style table that catches a shape mismatch when the pipeline is built, not deep in a hot loop. Operators that declare no signature show ? in that table, so the payoff grows as more operators declare one.

Closure discipline

toolz accepts any closure. That is right for interactive work and wrong for pipelines that must be audited: a closure cannot be inspected for what it captures, serialised, or rebuilt on a worker. pipekit’s answer is a class flag. Operators whose constructor takes a closure declare forbid_in_yaml = True (Tap, Lambda, Sink, Branch, Switch, Coalesce, ShapeTrace, Quarantine, AssertCallable), and a loader can refuse them. Operators that only nest other operators, such as Try, Retry or Cache, are not flagged: a walker finds the flagged children inside them. The dict and iterable operators, AssertThat and Log take operators or plain values instead of closures, so none of them is flagged, and a bare lambda handed to one is refused with a TypeError that names Lambda.

The trajectory: functions, Protocols, typed entities

The question is how pipekit moved from raw functions, through Protocols, to typed entities. The answer differs for the steps of a pipeline (operators) and for the data flowing through it (carriers), so the two are told separately.

Two lanes. Operators move from toolz functions through an OperatorLike Protocol to pipekit's Operator class, which is highlighted as settled. Carriers show Any in pipekit core, Array API Protocols in pipekit-array, and GeoTensor or xarray in geotoolz and xrtoolz, all in use at once.

Operators settled on a typed class; carriers use all three stages at once.

Operators

1 · Functions
2 · Protocols
3 · Typed base class

The toolz shape: an operator is a Python function. Maximum flexibility, zero boilerplate.

def my_op(x):
    return ...


pipe(value, my_op, other_op, third_op)

Buys you: any existing function adapts trivially, with no subclassing and no dependency beyond toolz.

Costs you: no config, no readable repr, no serialisation, no dispatch, no flags, no state, and no reuse beyond reusing the function.

Carriers

The carrier trajectory is different, and not settled.

1 · Any
2 · Protocols
3 · Concrete types

pipekit’s core uses Carrier = Any. The framework does not care what flows through; operators that need structure check it in their own signatures.

Buys you: maximum flexibility. Composition works the same whether the carrier is a NumPy array, an xr.DataArray, a DataFrame, an AnnData, a scalar or a user type, and test pipelines can run on scalars.

Costs you: operators that do want structure (named axes, coordinate systems, units) duck-check it every time, and there is no shared metadata surface.

Where pipekit lands

The two trajectories, resolved separately.

AxisWhere it landsStatus
Operatorsa typed concrete base class, pipekit_ops.Operatorsettled
Carriers, pipekit coreCarrier = Anysettled: the core stays carrier-agnostic
Carriers, multi-backendArray API Protocols, in pipekit-arraydispatch ships; the operator catalogue is in progress
Carriers, named dimsthe NamedArrayAdapter Protocol in pipekit-ops; DimArray and the dim functions in pipekit-arrayships
Carriers, domain librariesyour own: GeoTensor in geotoolz, xr.DataArray / xr.Dataset in xrtoolz, …in use

It was never one arc from functions to Protocols to typed entities. It was two trajectories that shared vocabulary. Operators started at toolz functions, considered Protocols, and landed on a typed base class. Carriers are still at all three stages at once, by design: each library uses the stage that serves it. Telling them as one story blurs the picture.

Why typed operators are not over-engineering

“Just use functions” is tempting: less code, faster to write, familiar to anyone who has used toolz, no subclassing.

The case for typed operators is that the six gaps above have no function-shaped solutions. Each needs somewhere to live: get_config on the operator, forbid_in_yaml on the class, dispatch in __call__, subclass walking in from_state. A function is the wrong host for all of them.

So the argument is not that classes beat functions. It is that the responsibilities pipekit takes on are class-shaped. Remove them (no introspection, no serialisation, no dispatch, no flags) and you are left with toolz, which is a perfectly good answer for problems that fit it. pipekit’s problems do not.

Where next

References