better-py

Curry

Currying and partial application

Currying

The curry decorator transforms a function with multiple arguments into a sequence of functions that each accept a single argument. This enables partial application—provide some arguments now, the rest later.

from better_py.functions import curry

@curry
def add(x, y, z):
    return x + y + z

add(1)(2)(3)  # 6 - one argument at a time
add(1, 2)(3)  # 6 - partial application

Calling add(1) returns a function waiting for the next argument. This is useful for creating specialized versions of general functions.

Partial Application from the Right

Fix arguments from the right side of a function. Unlike functools.partial which fixes from the left, partial_right is useful when the data you want to process should be the first argument.

from better_py.functions import partial_right

divide_by_2 = partial_right(lambda x, y: x / y, 2)
divide_by_2(10)  # 5

The divisor is fixed to 2, creating a reusable divide_by_2 function where the remaining argument becomes the dividend.

Flipping Arguments

Reverse the order of the first two arguments. This is helpful when adapting functions for use with pipe or flow, where the data should come first.

from better_py.functions import flip

subtract_from = flip(lambda x, y: x - y)
subtract_from(10, 3)  # 7 (10 - 3)

The original lambda subtracts y from x. After flipping, the first argument becomes the subtrahend and the second becomes the minuend.

Example: API Client

Currying is particularly useful for API clients where certain parameters remain constant:

@curry
def fetch(base_url, endpoint, params):
    return requests.get(f"{base_url}/{endpoint}", params=params)

api = fetch("https://api.example.com")
users = api("users", {"limit": 10})
posts = api("posts", {"author": 123})

The base URL is pre-filled, creating an api function that only needs the endpoint and parameters.

On this page