Functions are the central abstraction. They are values. Pass them, return them, store them, compose them.
def
7Default arguments
Hello, world!
Hi, world!Keyword arguments
123
123
123Variadic: *args and **kwargs
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 is rejected (as is any positional beyond the declared parameters when there is no *args), raising TypeError.
api:80 secure=False
api:443 secure=True
rejectedArgument unpacking at the call site
6
6
6
6lambda
Anonymous function. The body is a single expression.
42
7
Hi, worldFirst-class functions
Functions are values: store, pass, return them.
[3, '-0x3', '-3']7
12
4Higher-order functions
Functions that take or return functions.
25
108
13Closures
Functions capture their enclosing scope by reference.
1
2
310 11 12Currying
Partial application built from nested lambdas or closures.
7
13
10314 21Function composition
36
[4, 16, 36]Recursion
3628800True FalseGenerators
yield-bearing functions produce sequences lazily. Pull with next() or iterate with for.
0
1
4
9
16[1, 2, 3, 4, 5]yield from
Delegate to another generator.
[0, 1, 2, 10, 20]Generator expressions
Generators 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:
12Parameterised decorators are factories. A function takes the decorator args and returns the actual decorator. The wrapped function captures both scopes.
hi world
hi world
hi world