Chapter 10

Functional Programming in Python

10.0 Intro · 10.1 Functional Concepts · 10.2 Functional Practice

← → or Space to navigate · F for fullscreen

Learning Objectives

By the end of this chapter, you will be able to:

  1. Classify functions as pure or impure, and rewrite functions that mutate their inputs so that they return new values
  2. Pass, return, and wrap functions with lambda expressions, map(), filter(), sorted(), reduce(), closures, and decorators
  3. Rewrite map() and filter() pipelines as comprehensions, choose between the two styles, and refactor a loop into a pipeline of small pure steps
  4. Compare recursion with iteration, and write recursive functions for nested data
  5. Write context managers with @contextmanager, and use partial() and lru_cache() from functools where they are safe

What is Functional Programming?

Writing programs as transformations from inputs to outputs

Why Functional Programming?

Imperative approach

Describe each step and update state along the way.

prices = [10, 20, 30]
discounted = []

for price in prices:
    new_price = price * 0.9
    discounted.append(new_price)

Functional approach

Describe the transformation and produce a new value.

prices = [10, 20, 30]

discounted = [
    price * 0.9
    for price in prices
]

FP benefits: smaller functions, fewer side effects, easier testing, and clearer data pipelines.

Functional Vocabulary

Pure function Same input gives same output; no external changes.
Immutability Return new values instead of changing old ones.
First-class function Pass functions around like any other value.
Higher-order function Takes a function or returns a function.
Lambda Small anonymous function written inline.
Decorator Wraps a function with reusable behavior.

10.1 Functional Concepts

Purity, immutability, functions as values, lambdas, decorators, comprehensions, choosing a style

Two Paradigms, Compared

Feature Functional (FP) Object-oriented (OOP)
Core element Pure functions Objects and classes
State handling Immutability: return a new copy Mutability: objects modify their own data
Programming model Declarative: what to compute Imperative: how, step by step
Execution flow Recursion and pipelines (map, filter, reduce) Loops and ordered method calls
Strengths Predictable, easy to test, safer to share data Modeling entities, interfaces, domains

Typical emphasis, not a strict boundary: Python lets you mix both.

From Objects to Transformations

Shared design question: how do you organize a program so changes are easy to understand and control?

  • OOP groups related state and behavior behind clear interfaces.
  • FP makes calculation inputs and outputs explicit and limits hidden state changes.
  • A gradebook's methods can manage updates while pure helpers calculate averages, curved grades, and rankings.

Methods can return new values, and pure functions can accept objects.
Python lets these approaches work together.

A Gradebook: Complementary Contributions

Design concern OOP contribution FP contribution
Represent students and grades Maintain related data and enforce rules Consume well-defined records
Calculate curves or rankings Expose operations through methods Calculate without changing original grades
Record a grade change Update the gradebook explicitly Calculate proposed new values
Test the program Check behavior and state transitions Check inputs and expected outputs

Methods control updates; pure helpers calculate results.
A calculation can be tested without setting up the entire gradebook.

Pure Functions

  • Depend only on their arguments.
  • Return a value instead of modifying external state.
  • Easier to test because they are predictable.

Same input → same output. No hidden reads or writes.

# Pure
def add_tax(price, rate):
    return price * (1 + rate)

# Not pure: depends on global state
tax_rate = 0.07

def add_tax_global(price):
    return price * (1 + tax_rate)

Immutability

Functional code often returns a new value instead of changing an existing one.

  • Original data stays available.
  • Unexpected side effects are less likely.
  • Pipelines become easier to reason about.
  • Shared immutable data needs no updates coordinated between workers; other mutable state or resources may still need synchronization.
def add_item(items, new_item):
    return items + [new_item]

cart = ["book", "pen"]
new_cart = add_item(cart, "notebook")

print(cart)      # ['book', 'pen']
print(new_cart)  # ['book', 'pen', 'notebook']

Functions as Values

  • Assign a function to a variable.
  • Pass a function as an argument.
  • Return a function from another function.

This is the foundation for map, filter, decorators, callbacks, and custom sorting.

def square(x):
    return x * x

def apply(func, values):
    return [func(v) for v in values]

nums = [1, 2, 3, 4]
print(apply(square, nums))
# [1, 4, 9, 16]

Lambda Functions

A lambda is a small anonymous function for simple expressions.

Use case Example
Sort key key=lambda s: len(s)
Quick transform lambda x: x * 2
Pair key lambda item: item[1]

If the logic needs multiple steps, use def.

The name comes from lambda calculus, Alonzo Church's 1930s system of anonymous functions: the mathematical root of FP.

names = ["Ada", "Grace", "Linus"]

by_length = sorted(
    names,
    key=lambda name: len(name)
)

print(by_length)
# ['Ada', 'Grace', 'Linus']

Higher-Order Functions

A higher-order function works with other functions.

  • Takes a function as input.
  • Returns a function as output.
  • Builds reusable behavior without duplicating control flow.
  • make_multiplier returns a closure: multiply remembers factor (see 4.2).
def make_multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)

print(double(10))  # 20
print(triple(10))  # 30

A Closure Trap: Late Binding

A closure remembers the variable, not its value at creation. The variable is looked up when the function is called.

  • All three lambdas share one i.
  • After the loop, i is 2.
  • Fix: a default argument i=i, or a factory function such as make_multiplier(i).
funcs = [lambda x: x * i for i in range(3)]
[f(10) for f in funcs]   # [20, 20, 20]

funcs = [lambda x, i=i: x * i for i in range(3)]
[f(10) for f in funcs]   # [0, 10, 20]

Decorators

  • A decorator takes a function and returns a wrapped function.
  • Use for logging, timing, validation, caching, and access checks.
  • @decorator syntax replaces manual wrapping: greet = announce(greet).
  • Stacked decorators apply bottom-up: @a above @b means a(b(f)).
def announce(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@announce
def greet(name):
    return f"Hello, {name}"

print(greet("Ada"))

Functional Tools and Pure Behavior

Function passing and wrapping describe structure. Purity describes behavior.

Example Classification Why
apply_twice with a pure callback Pure computation No hidden state or side effects
greet wrapped by announce on the previous slide Impure call The wrapper prints, even though the greeting is predictable
Notebook slow_add with a timer wrapper Impure call Waits, reads a clock, and prints
Notebook greet wrapped by shout Pure call Pure string construction followed by uppercase conversion

Printing a returned result in the caller does not make the function impure.
Adding logging inside a callback makes the composition impure.

Built-in Decorators

Decorator What it does
@property Turns a method into a managed attribute: computed, validated, or read-only
@staticmethod Method needs neither self nor cls (9.3)
@classmethod Method receives the class as cls (9.3)
@functools.wraps Used inside custom decorators to keep the original name and docstring

wraps preserves metadata for inspection and help(); tracebacks can still show a wrapper frame.

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @property
    def area(self):
        return math.pi * self.radius ** 2

c = Circle(5)
print(round(c.area, 2))   # 78.54, no parentheses

Map, Filter, and Comprehensions

Functional tools

nums = [1, 2, 3, 4, 5]

squares = list(map(lambda n: n*n, nums))
evens   = list(filter(lambda n: n % 2 == 0, nums))

Pythonic alternative

nums = [1, 2, 3, 4, 5]

squares = [n*n for n in nums]
evens   = [n for n in nums if n % 2 == 0]

In Python, comprehensions are often clearer than map and filter with lambdas.

Choosing a Style

Use functional style when…

  • You are transforming collections.
  • A pure helper function makes logic easier to test.
  • A comprehension or small pipeline is clearer than a loop.

Prefer another style when…

  • The lambda becomes hard to read.
  • The code needs several statements or error handling.
  • Mutating state is the simplest honest model.
  • Remember that map() and filter() are lazy iterators you can consume only once.

Python supports multiple styles. The goal is readable, testable code — not functional purity.

Designing a Pipeline: Record Shapes

Inventory task: keep quantities of at least three, then rank highest first.
Each record has a colon and a fruit name; quantity is blank or nonnegative integer text.

Stage Example input Example output
Parse and normalize ' apple : 3 ' ('Apple', '3')
Remove missing values and convert ('Apple', '3') ('Apple', 3)
Select stock ('Apple', 3) Keep if quantity is at least three
Rank selected records List of tuples Descending quantity order

Name boundaries where a record's meaning or representation changes.
Remove blank quantities before int(); compare quantities only after conversion.

Worked Inventory Pipeline

raw_inventory = [' apple : 3 ', 'banana:', 'pear:0', 'orange:5']

def parse_inventory(line):
    fruit, _, text = line.partition(':')
    return fruit.strip().title(), text.strip()

parsed = [parse_inventory(line) for line in raw_inventory]
converted = [(fruit, int(text)) for fruit, text in parsed if text != '']
stocked = [item for item in converted if item[1] >= 3]
ranked = sorted(stocked, key=lambda item: item[1], reverse=True)
print(ranked)  # [('Orange', 5), ('Apple', 3)]

Inspect each intermediate collection, compare with the loop baseline,
and check that the original input is unchanged. These lists use memory.

Bridge: From Pipelines to pandas

Plain Python pandas
map(f, items) series.map(f)
function on a whole record df.apply(f, axis=1)
filter() / if clause df.query(...)
sorted(key=...) df.sort_values(...)
named intermediate lists method chain
top = (
    df.assign(curved=lambda d: d['score'].map(make_curve(5)))
      .query('curved >= 80')
      .sort_values('curved', ascending=False)
)

Each step returns a new DataFrame. Prefer column operations such as df['score'] + 5 over .map() or .apply() when they exist.

10.2 Functional Practice

Recursion, context managers, and practical tools from functools

Recursion: Recap and Trade-offs

Recap from 4.3 Recursion: a base case stops the calls, and a recursive case calls the function on a smaller problem.

  • Fits functional style: repeats work without mutating a loop counter.
  • Good fit for self-similar structure such as trees and nested folders.
Recursion Iteration
Mirrors math definitions Usually faster in Python
Natural for tree traversal No recursion limit
Extra call overhead Uses less memory
Limit near 1000 calls; deeper raises RecursionError Can be harder to read for nested data

lru_cache (later in 10.2) caches a recursive function such as fib.

Recursion on Nested Data

A list inside a list has no fixed depth, so a fixed set of nested loops cannot reach every level.

  1. Base case: not isinstance(data, list) means a number with nothing inside.
  2. Recursive case: call the function on each element and combine the returned values.

depth([1, [2, [3]]]) asks about 1 (0) and [2, [3]] (2), then returns 1 + 2 = 3.

def depth(data):
    if not isinstance(data, list):
        return 0
    deepest = 0
    for item in data:
        deepest = max(deepest, depth(item))
    return 1 + deepest

depth([1, [2, [3]]])   # 3

Use a loop instead for a flat sequence: recursion adds a frame per value.

Context Managers

A context manager handles setup and cleanup around a block of code.

  • Open and close files safely.
  • Acquire and release resources.
  • Keep cleanup reliable even when errors happen.
  • Packages the try/finally pattern you would otherwise repeat at every use.
from contextlib import contextmanager

@contextmanager
def section(name):
    print(f"Start {name}")
    try:
        yield
    finally:
        print(f"End {name}")

with section("demo"):
    print("working")

The functools Module

Tool Use
reduce Combine many values into one
partial Pre-fill some function arguments
lru_cache Memoize expensive function calls

Use these when they simplify the code. Do not force them into every problem.

from functools import reduce, partial, lru_cache

total = reduce(lambda a, b: a + b, [1, 2, 3])

# initializer: needed when items are not the result type
students = [("Alice", 85), ("Bob", 90), ("Charlie", 78)]
grade_sum = reduce(lambda acc, s: acc + s[1], students, 0)   # 253
reduce(lambda acc, x: acc + x, [], 0)                       # 0, no TypeError

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)

@lru_cache
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

Hits and Misses: Tracing ways(4)

With an empty cache, the first call to each of ways(4), ways(3), ways(2), ways(1), and ways(0) is a miss: 5 misses.

Two later requests find a saved answer: ways(1) inside ways(3), and ways(2) inside ways(4): 2 hits.

A second top-level ways(4) is a hit that never runs the body: hits become 3, misses stay 5.

When Is Caching Safe?

Check Risk on a cache hit
Arguments are hashable Lists and dictionaries cannot be cache keys
Answer depends only on arguments Changing external state can leave stale answers
Skipping the body is safe Logging and other side effects do not run again
Reusing the same result object is safe A cached list is shared between callers

maxsize=2 keeps two entries; @lru_cache() defaults to 128.
maxsize=None never evicts entries and can grow without bound.
Cached arguments and results stay referenced until eviction or clearing.

A Stale Cached Answer

settings = {'bonus': 5}

@lru_cache(maxsize=2)
def curved_score(score):
    return min(score + settings['bonus'], 100)

print(curved_score(80))       # 85
settings['bonus'] = 10
print(curved_score(80))       # 85: same key, stale result
curved_score.cache_clear()
print(curved_score(80))       # 90: recomputed

Prefer explicit inputs: curved_score(score, bonus) makes the bonus part of the key.
For fresh mutable results, leave the function uncached or copy cached immutable data.

Choose a Tool and Predict the Cache

  1. Specialize meets_minimum(grade, minimum) into a predicate for grades of at least 80. Choose partial or a closure and justify it; use it with filter.
  2. After count_ways.cache_clear(), predict the returned value and cumulative hits/misses after each of two calls to count_ways(5). Then run and inspect cache_info().
  3. A live score lookup reads a changing dictionary by student name. Would partial, lru_cache, or neither keep its answers current? Explain.

Use the notebook's final functools exercise to implement and check your answers.

Chapter 10 — Quick Reference

Concept Key syntax / notes
Pure function No side effects; depends only on arguments
Immutable update Return a new value instead of mutating the original
Lambda lambda args: expression
Map / filter map(func, xs), filter(pred, xs)
Comprehension [expr for item in xs if condition]
Decorator @decorator wraps a function
Recursion Base case plus recursive case
Context manager with manager: handles setup and cleanup
functools reduce, partial, lru_cache

End of Chapter 10

Next: Chapter 11 — Iterators & Generators

iterators · generators · yield · itertools