Functions
Any parameter can be passed by name, defaults are common, and functions are ordinary values you can pass around.
def f(a, b=2, *args, c, **kwargs): ... # │ │ │ │ └─ extra keyword args → dict # │ │ │ └─ keyword-only (it comes after *args) # │ │ └─ extra positional args → tuple # │ └─ default value # └─ required
- Defaults are evaluated once, when the
defline runs. A mutable default such as[]is therefore shared between calls. This is a classic bug. lambda x: x * 2can hold only one expression. For anything bigger, use adef.- To reassign a variable from an outer function, use
nonlocal(orglobalfor module level). Reading it needs nothing. - Decorators (
@cache,@dataclass) are functions that wrap functions. They look like Java annotations, but they actually run code.
def connect(host, port=5432, *, timeout=10):
...
connect("db", timeout=3)def describe(name, *tags, sep=", ", **extra):
print(name, "|", sep.join(tags), "|", extra)
describe("ana", "admin", "dev", sep=" / ", team="core")
args = ["bo", "ops"]
opts = {"sep": "+", "on_call": True}
describe(*args, **opts) # spread like JS ...
double = lambda x: x * 2
print(list(map(double, [1, 2, 3])))
print(sorted(["kiwi", "fig", "banana"], key=len)) # functions as valuesdef add(item, items=[]):
items.append(item)
return items
print(add("x"))
print(add("y"))This code has a bug. Fix it. It should append item to items and return the list, using a fresh list when none is passed in.
add_item("x") → ["x"], and then add_item("y") → ["y"]. Right now the second call returns ["x", "y"].
Return a function that returns 1, then 2, then 3, and so on, one number per call. Each counter is independent.
c = make_counter(); c() → 1; c() → 2
Pass value through each function in order and return the result.
apply_all(3, lambda x: x + 1, lambda x: x * 10) → 40
Add query parameters to a URL, in the order they were given.
build_url("https://x.com/search", q="cats", page=2) → "https://x.com/search?q=cats&page=2"
build_url("https://x.com") → "https://x.com"