Functions as first-class objects and higher-order functions
'First-class' means functions are ordinary values: they are objects of type function, so you can assign them to variables, store them in lists and dicts, pass them as arguments, return them from other functions, and attach attributes to them. A higher-order function is one that takes a function as an argument, returns one, or both. This is the foundation of decorators, callbacks, key functions for sorting, dispatch tables, functools utilities and closures.
Why this works in Python: a def statement creates a function object (with code, defaults, closure, dict) and binds it to a name, exactly like assigning any object. Calling is just the () operator applied to any callable, which includes functions, bound methods, classes and instances that define call. The expression f refers to the function while f() calls it; confusing the two (for example sorted(x, key=f()) ) is a common beginner bug. Functions accessed through an instance become bound methods via the descriptor protocol, which is how self gets passed.
Practical trade-offs: dispatch tables (dict of functions) replace long if/elif chains and are easy to extend, but are less explicit for complex conditions. lambda is limited to a single expression, so use def for anything more; operator.itemgetter and attrgetter are faster and clearer for simple sort keys. Comprehensions are usually more readable than map and filter with lambdas. functools.partial pre-fills arguments, and closures do the same with more flexibility but with late-binding pitfalls when created in loops.
Common mistakes: forgetting functools.wraps in decorators so introspection, logging and frameworks that rely on name or signature break; creating closures in loops that capture the variable instead of its value; and over-abstracting with deeply nested decorators that make stack traces and debugging harder. Higher-order functions are also how frameworks like Flask routes, pytest fixtures and middleware pipelines are built.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience