Skip to content

Instantly share code, notes, and snippets.

@stuarteberg
Last active August 19, 2025 02:10
Show Gist options
  • Save stuarteberg/6bcbe3feb7fba4dc2574a989f196ee11 to your computer and use it in GitHub Desktop.
Save stuarteberg/6bcbe3feb7fba4dc2574a989f196ee11 to your computer and use it in GitHub Desktop.
pipe_in_python.py
from collections.abc import Callable, Iterable
from functools import partial
# See discussion in https://news.ycombinator.com/item?id=44942936
def pipe(orig, *transforms):
result = orig
for transform in transforms:
if isinstance(transform, Callable):
result = transform(result)
else:
assert isinstance(transform, Iterable)
result = partial(*transform)(result)
return result
# Example
times_two = lambda x: x * 2
plus_one = lambda x: x + 1
plus_c = lambda x, c: x + c
pipe(
0,
plus_one,
times_two,
# to supply positional args only, use a tuple
(plus_c, 4),
# to supply keyword args, use partial
partial(plus_c, c=4)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment