// REF. 08 / PYTHON

Python cheat sheet

The Python you actually type: comprehensions, unpacking, f-strings, dataclasses, pattern matching, the typing syntax that stopped needing TypeVar, and the asyncio calls that do not leak tasks. Current to Python 3.15.2 (with 3.14.10 in bugfix), checked against docs.python.org in October 2026.

Two habits worth the desk space: reach for f"{x=}" before print("x", x), and let uv run own the virtualenv so you never have to remember which one is active.

↓ Download the printable PDF free · letter size · no email needed

Idioms

[x*2 for x in xs if x]
list comprehension with filter
{k: v for k, v in pairs}
dict comprehension
(x for x in xs)
generator: lazy, one pass
[*a, *b] / {**d1, **d2}
splice lists / merge dicts, right wins
if m := re.search(p, s):
walrus: assign and test in one go
enumerate(xs, start=1)
index and item, counting from 1
zip(xs, ys)
iterate in lockstep

F-strings

f"{x=}"
debug: prints x=value
f"{n:,}"
thousands separator
f"{v:.2f}"
two decimal places
f"{", ".join(xs)}"
same quotes inside — 3.12+
t"Hi {name}"
template string, not a str — 3.14+

Functions & types

def f(a, /, b, *, c):
a positional-only, c keyword-only
type Pair[T]=tuple[T,T]
generic alias — 3.12+
class Box[T]: ...
generic class, no TypeVar
def f[T](x: T) -> T:
generic function
x: int | None = None
optional without Optional[]
-> TypeIs[str]
narrowing predicate — 3.13+

Dataclasses

@dataclass
__init__, __repr__, __eq__ for free
@dataclass(frozen=True)
immutable; fields can't be set
field(default_factory=f)
mutable default, done right
kw_only=True
fields must be passed by keyword
replace(obj, x=5)
copy with changes

Match

match cmd:
structural pattern matching
case [x, y]:
sequence pattern, binds x and y
case {"id": i, **rest}:
mapping pattern, extra keys ignored
case Point(x=0, y=y):
class pattern
case (x, y) if x == y:
guard
case _:
wildcard, never fails

Errors

except ValueError as e:
catch and bind
except A, B:
several types, no parens — 3.14+
else: / finally:
ran clean / runs no matter what
raise X from e
explicit chain; from None hides it
except* OSError:
matching members of an ExceptionGroup
e.add_note("ctx")
append context to the traceback

Files & contexts

Path("a") / "b.txt"
join paths with /
p.read_text()
whole file as str; write_text too
p.mkdir(parents=True)
mkdir -p; add exist_ok=True
Path(".").rglob("*.py")
recursive glob
p.name, p.stem, p.suffix
grail.tar.gz, grail.tar, .gz
@contextmanager
generator: setup, yield, teardown

Async

asyncio.run(main())
run the event loop to completion
asyncio.create_task(c())
schedule now, await later
asyncio.TaskGroup()
async with; awaits all on exit
asyncio.gather(a(), b())
run together, results in order
asyncio.timeout(10)
async with; TimeoutError past it

Tooling

python -m venv .venv
then source .venv/bin/activate
uv add requests
add dependency, update lockfile
uv sync
match the env to the lockfile
uv run script.py
run inside the project env
uvx ruff
run a tool in a throwaway env
Python Field Manual Desk Mat

// KEEP IT UNDER YOUR KEYBOARD

Python Field Manual Desk Mat

from $34 · printed to order in the USA

See the desk mat