Functional Programming

Functional programming emphasizes function composition, higher-order functions, and explicit data transformations. Pure functions and immutable data are core tools, while real-world applications still manage file and network side effects at the boundary.

One-Line Definition

Functional programming emphasizes function composition, higher-order functions, and explicit data transformations. Pure functions and immutable data are core tools, while real-world applications still need to manage file, network, and other side effects cleanly.

Why It Matters

  • Pure functions are effortless to test: Identical inputs always produce identical outputs, so unit tests never have to mock or set up external "world state."
  • Naturally suited for parallelism and caching: Reducing shared mutable state lowers race-condition risks in core logic; when outputs depend strictly on inputs, results are safe to memoize—provided you still verify argument hashability, return-value mutability, and cache capacity (see functools.cache in k1.py.decorator).
  • Data pipeline mindset: Data cleaning, feature engineering, and ETL pipelines are sequences of step-by-step transformations, which functional composition expresses naturally.

Operating Boundaries

Immutability in Python usually describes only the container object itself: a list stored inside a tuple or a frozen=True dataclass can still be mutated in place. Memoization also requires hashable inputs and outputs that remain valid for the cache's lifetime, and pure functions do not eliminate concurrency hazards in surrounding I/O layers.

How It Works / Diagram

The four core building blocks:

Concept Meaning How It Appears in Python
Pure function No side effects; output depends solely on arguments Does not read/write global state or mutate input arguments
Immutable data Never modified after creation; updates return a new value tuple, frozenset, frozen=True dataclasses, and frozendict added in Python 3.15
First-class / higher-order functions Functions can be passed as arguments and returned as values map, filter, sorted(key=...), decorators
Composition Chaining small functions into a larger transformation compose(f, g, h), method chaining
Figure 1

Python 3.15 (released October 9, 2026) adds a built-in frozendict type (PEP 814), which is hashable whenever all of its keys and values are hashable—rounding out Python's built-in immutable data structures: https://docs.python.org/3.15/whatsnew/3.15.html, https://peps.python.org/pep-0814/

Runnable Example

# File: examples/04_functional.py
# Functional programming: pure functions, immutable data, first-class functions, composition
from functools import reduce, partial

def compose(*fs):
    return lambda x: reduce(lambda acc, f: f(acc), fs, x)

strip = str.strip
lower = str.lower
def remove_punct(s): return "".join(c for c in s if c.isalnum() or c.isspace())

normalize = compose(strip, lower, remove_punct)
print(repr(normalize("  Hello, World!  ")))

# Pure function vs. function with side effects
counter = 0
def impure_add(x):
    global counter
    counter += x          # Mutating external state = side effect
    return counter
def pure_add(acc, x):
    return acc + x        # Depends strictly on inputs
print("Impure:", impure_add(1), impure_add(1))   # Same input, different outputs
print("Pure:", pure_add(0, 1), pure_add(0, 1))   # Same input, identical outputs

# Immutable data: return a new object instead of mutating the old one
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class User:
    name: str
    level: int
u1 = User("ann", 1)
u2 = replace(u1, level=2)
print(u1, u2)

# Higher-order functions and partial application
power = lambda base, exp: base ** exp
square = partial(power, exp=2)
print(list(map(square, [1, 2, 3])))

Recorded output (Python 3.15.0):

'hello world'
Impure: 1 2
Pure: 1 1
User(name='ann', level=1) User(name='ann', level=2)
[1, 4, 9]

Look at lines 2 and 3 of the output: calling impure_add(1) twice returns different results (1 and 2) because it silently mutates the global counter, whereas pure_add(0, 1) always returns 1. That is the concrete difference between a side effect and a pure function.

Common Pitfalls

  • "Using map and lambda makes my code functional": What matters is eliminating hidden side effects, not surface syntax. A lambda inside map that mutates a global dictionary or writes to disk is still imperative code.
  • Forcing "pure functional" idioms onto Python: Python does not perform tail-call optimization (deep recursion raises RecursionError), and list comprehensions are almost always more readable than map(lambda ...). Python's official HOWTO likewise recommends list comprehensions and generator expressions: https://docs.python.org/3/howto/functional.html
  • "Immutable means slow": Allocating small value objects is inexpensive; large numerical arrays and tables are handled in compiled C/Rust layers by NumPy or Polars. Returning new views or objects prevents accidental mutation, though note that a pandas DataFrame remains mutable unless Copy-on-Write rules apply (see k1.lib.pandas).
  • Trying to eliminate side effects entirely: Real programs eventually have to write files and send network requests. The practical architecture is to push side effects to the outer boundary while keeping core transformations pure ("functional core, imperative shell").

Relevance to AI Engineering

  • JAX requires pure functions: jax.jit and jax.grad only behave predictably on pure functions; mutating global Python state inside a JIT-compiled function produces undefined behavior during tracing: https://docs.jax.dev/en/latest/notebooks/Common_Gotchas_in_JAX.html
  • Data preprocessing pipelines (such as Hugging Face datasets.map and Polars expressions) are structured around pure row/batch transformations (take a row or column in, return a new row or column out), enabling automatic multiprocessing and fingerprint-based caching.
  • Agent tool / function calling: The closer an LLM tool function is to a pure function (explicit parameters, no hidden session state), the easier it is to replay, test, and evaluate agent trajectories deterministically.

Further Reading

Concept Check

If you put a Python list inside a frozen=True dataclass, can the contents of that list still be modified?

Reference answer: Yes. frozen=True only blocks reassigning the dataclass attribute itself; it does not recursively freeze mutable objects referenced by that attribute.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Execution log: 04_functional.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram