Compose
Function composition utilities
Function Composition
Combine multiple functions into a single function where each function's output becomes the next function's input. Functions execute right-to-left, following mathematical convention.
from better_py.functions import compose
double = lambda x: x * 2
increment = lambda x: x + 1
transform = compose(double, increment)
transform(5) # 12: increment(5) → 6, then double(6) → 12Reading right-to-left: increment runs first, then double. The result is a reusable transformation pipeline.
Left-to-Right Composition
Same as compose but executes left-to-right, which can be more intuitive for data pipelines.
from better_py.functions import compose_left
transform = compose_left(increment, double)
transform(5) # 12The execution order matches the reading order. Choose based on which direction feels natural for your use case.
Example: Validation Pipeline
Composition is useful for validation and data processing chains where each step is a pure, single-responsibility function:
def get_user(id):
return {"id": id, "role": "admin"}
def check_perms(user):
return user if user["role"] == "admin" else None
def check_auth(user):
return user if user else None
validate = compose(check_auth, check_perms, get_user)
validate(123) # Returns user object or NoneData flows through each function: get_user fetches the user, check_perms verifies admin role, and check_auth performs final validation.
Reference
| Function | Direction | Returns |
|---|---|---|
compose | Right-to-left | Function |
compose_left | Left-to-right | Function |
pipe | Left-to-right | Value |
Use compose when you need a reusable function. Use pipe to execute a chain immediately on a value.