First-class functions
Functions are first-class values in Python: you can assign them, store them, pass them as arguments, and return them from other functions. A function that takes or returns a function is called higher-order.
Detailed Explanation
In some languages a function is a special kind of thing you can only call. In Python a function is an object like a string or a list. def greet(name): creates a function object and binds the name greet to it. notify = greet makes a second name for the same object. notify("ada") calls it. Nothing about the object changed.
That property is what makes callbacks, decorators, and strategy objects cheap. sorted(rows, key=lambda row: row["created_at"]) works because sorted accepts a function and calls it once per element. map, filter, max, and min do the same. You are not subclassing a Comparator interface. You are handing over a callable.
Callables are broader than def functions. A class with __call__, a bound method, a functools.partial, a lambda, and a type object (int("4")) are all callable. callable(x) reports whether x(...) is legal. Libraries that accept a "hook" should accept any callable, not only functions created with def.
Returning a function is how closures are born. An outer function can define an inner one that reads the outer locals, then return the inner function. The inner function keeps those values alive after the outer call has finished. Decorators are this pattern plus rebinding. So are factories that configure a function once and reuse it.
First-class functions replace a surprising amount of object-oriented ceremony. A one-method strategy class is often a function. A registry of handlers is a dict of functions. A plugin system is a list of callables. Use a class when you need shared mutable state, inheritance, or more than one related operation. Use a function when you need one operation.
Names and functions are not the same thing. Deleting or rebinding greet does not destroy the object if another name still refers to it. That is ordinary object lifetime. It is also why handlers.append(greet) stores the function, not the name: later rebinding greet leaves the list unchanged.
Code Examples
def greet(name: str) -> str:
return f"hello {name}"
notify = greet # second name, same function object
print(notify("ada")) # hello ada
print(notify is greet) # True
# Pass a function as data.
users = ["ada", "linus", "grace"]
print(sorted(users, key=len)) # ['ada', 'grace', 'linus']# Return a configured function. The inner function closes over `prefix`.
def prefixed(prefix: str):
def format_sku(code: str) -> str:
return f"{prefix}-{code}"
return format_sku
eu_sku = prefixed("EU")
print(eu_sku("1044")) # EU-1044# A registry of callables is a first-class-function design.
def ship_ground(order_id: str) -> str:
return f"{order_id} by truck"
def ship_air(order_id: str) -> str:
return f"{order_id} by air"
carriers = {"ground": ship_ground, "air": ship_air}
print(carriers["air"]("ORD-7")) # ORD-7 by air
print(callable(int), int("21")) # True 21Common Gotchas
Passing `func()` instead of `func` calls it immediately
`key=len("ada")` passes `3`, not a function, and `sorted` then fails. Pass the function object; the callee will call it.
Late binding in closures
a function defined inside a loop sees the variable's value at call time, not at definition time. Bind the current value with a default argument: `lambda n=n: n`.
Methods are functions plus an instance
`user.rename` is a bound method. Storing it keeps the instance alive. That is useful for callbacks and expensive if you did not mean to retain the object.
`lambda` cannot contain statements
use `def` the moment you need a name, a guard clause, or more than one expression.