Handbooks / Python / Chapter 2
Functions and Closures
7 pages · ~5 min✓ Reviewed
Builds on Types and Data Structures. Next up: Errors and the Standard Library.
Functions as Objects: Mental Model
1. Functions Are Objects
defbuilds a function object and binds it to a name- Assign it, or store it in a list or dict
- Pass it as an argument, or return it
python
def f(x): return x * 2 g = f ops = {'dbl': f} del f print(g(2), ops['dbl'](3))
del f removes one name, not the object
output
4 6
2. Higher-Order Functions
| Call | Function argument |
|---|---|
sorted(words, key=len) | len computes the sort key |
map(str.upper, xs) | str.upper applied to each item |
filter(None, xs) | None keeps only truthy items |
def make(): return f | returns a function |
3. Names and Callables
g = f: two names, one objectcallable(obj)is True for functions, classes, objects with__call__
4. Interview Point
- Function as dict value? It is an ordinary object
- What makes it callable? A
__call__method
Arguments: Positional, Keyword, *args, **kwargs
1. Signature order
- Positionala
- Defaultb=1
- *argstuple
- Keyword-onlyc, d=2
- **kwargsdict
Default Argument Pitfalls
1. Evaluated Once
- Defaults are built once, at
deftime - Stored in
f.__defaults__, reused on every call - Safe: int, str, tuple, None
- Danger: a default that is mutated or reused
2. The Trap and the Fix
add(1)thenadd(2)share one list, giving[1, 2]
Scope (LEGB) and Closures
1. LEGB and Rebinding
- Localinside def
- Enclosingouter def
- Globalmodule
- Built-inlen, print
- First match wins; no match raises
NameError - Assigning anywhere in a def makes the name local for the whole function
- Reading it before the assignment raises
UnboundLocalError global x/nonlocal xonly to rebind; reading or mutating needs neither
Lambdas and Decorators
1. Lambda
lambda args: expr= one expression, anonymous- No statements, no annotations
- Best as a
key=:sorted(users, key=lambda u: u.age)
2. Decorators
@decabovedef fis exactly f = dec(f)- Wrapper takes
*args, **kwargs: fits any signature
Cheat Sheet: Functions, Scope and Decorators
1. Arguments and defaults
python
def f(a, b=1, *args, kw, kw2=2, **kwargs): ... def g(a, /, b, *, c): ...
order: positional, default, *args, keyword-only, **kwargs
/ends positional-only;*or*argsstarts keyword-only- Mutable default like
acc=[]is shared by every call - Fix:
acc=None, then createacc = []inside the body
2. Scope and closures
Check yourself
What does the last line print?
[1, 2]- The default list is built once at
deftime, so both calls share it - Fix:
acc=None, thenacc = [] if acc is None else acc
def add(x, acc=[]): acc.append(x) return acc add(1) print(add(2))
What is printed, and how do you get [0, 1, 2]?
[2, 2, 2]- Each lambda looks up
iwhen called, after the loop has ended