Skip to content

Instantly share code, notes, and snippets.

@smcl
Last active August 5, 2025 20:09
Show Gist options
  • Select an option

  • Save smcl/470dee1dadaf45644b144c69d7684126 to your computer and use it in GitHub Desktop.

Select an option

Save smcl/470dee1dadaf45644b144c69d7684126 to your computer and use it in GitHub Desktop.
doodling a bit with piping/composition/partials in Python
from functools import reduce, partial
"""
After PHP announced the pipe operator[0] I got wondering what it might look
like in Python. I actually fucked up and started implementing something
different - the >> operator rather than the |> one. Oops.
Anyway it turns out that it is pretty easy to do simple composition with
partial functions. It's quite a crummy approximation of proper functional
programming like in ML or Haskell. There isn't a nice |> operator nor any
simple way to do implement it without digging into CPython itself, and
after that you'd have a lot of fun figuring out how to get mypy to do
typechecking.
[0] https://thephp.foundation/blog/2025/07/11/php-85-adds-pipe-operator/
"""
# our |> is just a function uses reduce() to chain some funcs together
def compose(*funcs):
def inner(arg):
return reduce(lambda arg, func: func(arg), funcs, arg)
return inner
# define a couple of simple functions we'll use here
def add(x: int, y: int) -> int:
return x + y
def multiply(x: int, y: int) -> int:
return x * y
add_one_then_times_ten = compose(
lambda x: add(1, x),
lambda x: multiply(10, x),
)
times_ten_then_add_one = compose(
lambda x: multiply(10, x),
lambda x: add(1, x),
)
assert 20 == add_one_then_times_ten(1)
assert 11 == times_ten_then_add_one(1)
# kind of a big part of how this works in functional programming is
# currying or partial application, we can do it in Python but it
# is a little goofy
add_two_then_times_twenty = compose(
partial(add, y=2),
partial(multiply, y=20),
)
times_twenty_then_add_two = compose(
partial(multiply, y=20),
partial(add, y=2),
)
assert 60 == add_two_then_times_twenty(1)
assert 22 == times_twenty_then_add_two(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment