Python for Polyglots
Lesson 7 · Core

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 def line runs. A mutable default such as [] is therefore shared between calls. This is a classic bug.
  • lambda x: x * 2 can hold only one expression. For anything bigger, use a def.
  • To reassign a variable from an outer function, use nonlocal (or global for module level). Reading it needs nothing.
  • Decorators (@cache, @dataclass) are functions that wrap functions. They look like Java annotations, but they actually run code.
Defaults & named arguments
def connect(host, port=5432, *, timeout=10):
    ...

connect("db", timeout=3)
Experiment
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 values
Quiz: What does the second call print?
def add(item, items=[]):
    items.append(item)
    return items

print(add("x"))
print(add("y"))
Exercise 18: Fix the mutable default

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"].

Exercise 19: A counter closure

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

Exercise 20: Pipeline of functions

Pass value through each function in order and return the result.

apply_all(3, lambda x: x + 1, lambda x: x * 10) → 40

Exercise 21: Build a URL

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"