Compose Small Transformations
Core idea
Function composition passes the result of one function into another. For unary functions f and g, g(f(value)) applies f first. A composition helper can return a reusable closure. Make sure each stage returns a value suitable for the next stage; Python does not automatically adapt incompatible function signatures.
def clean(text): return text.strip()def upper(text): return text.upper()print(upper(clean(" box-a ")))The inner call trims whitespace before the outer call changes case.
Build a reusable composition
def compose(g, f): def combined(value): return g(f(value)) return combinedscale_then_fee = compose(lambda n: n + 4, lambda n: n * 2)print(scale_then_fee(5))The closure retains both functions and applies the inner function first.
Compare stage order
def double(n): return n * 2def add_fee(n): return n + 3print(add_fee(double(4)), double(add_fee(4)))Reordering operations can change the result.
Common mistake
Composition is not commutative in general. Do not hide effects or error-handling requirements in long chains; named intermediate values may be clearer.
Practice
Compose a function converting text to an integer with a function that doubles it. Test valid signed text and explain how invalid input propagates ValueError.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Composition
Check your understanding of function composition.
What is printed?
f = lambda x: x * 2g = lambda x: x + 1print(g(f(3)))What is printed?
print(str.upper(str.strip(" a ")))What is printed?
def compose(g, f): return lambda x: g(f(x))h = compose(lambda x: x * 3, lambda x: x + 2)print(h(2))What is required for g(f(value)) to work?