Functions are values. Pass them, return them, store them, compose them.
def
7Default arguments
Hello, world!
Hi, world!Keyword arguments
123
123
123Variadic parameters
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dict.
6
60[('host', 'api'), ('port', 443)]Keyword-only parameters
A bare * marks the following parameters as keyword-only. They must be passed by name. A positional argument that would reach them raises TypeError, as does any positional argument beyond the declared parameters when there is no *args.
api:80 secure=False
api:443 secure=True
rejectedArgument unpacking at the call site
6
6
6
6lambda
An anonymous function. The body is a single expression.
42
7
Hi, worldFirst-class functions
Store functions in data structures and pass them as arguments.
[3, '-0x3', '-3']7
12
4Function attributes
Functions carry writable attributes, like any object. getattr / hasattr / setattr / delattr work on them, and an assigned __name__ wins over the declared one. Decorators use these for metadata.
10
n/a
TrueHigher-order functions
Functions that take or return functions.
25
108
13Closures
An inner function captures the variables of its enclosing scope by reference.
1
2
3Because capture is by reference, every lambda in a loop sees the same loop variable. Bind the current value through a default argument.
10 11 12global and nonlocal
Assignment inside a function creates a local unless declared otherwise. nonlocal name rebinds the nearest enclosing function’s variable. That is the shared cell the counter closure above relies on. global name rebinds the module-level variable.
7Reading an outer variable needs no declaration. Only rebinding does.
15Recursion
3628800True FalseGenerators
A function containing yield produces its sequence lazily. Pull values with next() or iterate with for.
0
1
4
9
161
2[1, 2, 3, 4, 5]yield from
Delegate to another generator or any iterable.
[0, 1, 2, 10, 20]yield from is also an expression. It evaluates to the subgenerator’s return value, so a generator can pass a result back to its delegating caller.
returned done
[1, 2]Generator expressions
A generator inline.
30
5Decorators
A decorator wraps another callable. It applies to both functions and classes (see Classes).
calling with (3, 4)
7Stacked decorators apply bottom-up.
12A parameterized decorator is a factory. The outer function takes the decorator arguments and returns the actual decorator. The wrapped function captures both scopes.
hi world
hi world
hi world