Stas' Python Cookbook

July 1, 2026 · View on GitHub

Distilled from Stas' Python Cookbook open book by Stas Bekman - source: https://github.com/stas00/python-cookbook (CC BY-SA 4.0). This skill is a condensed index; each section links back to the full chapter for depth, runnable snippets, and gotchas.

A practical, standard-library-first reference for the Python idioms that come up again and again in real work. It leads with the why, shows the how with copy-paste snippets, and calls out the gotchas that bite in practice. Targets Python 3.8+; version-specific features are flagged inline. For deep single-process/tool debugging (gdb, strace, py-spy, core files, CUDA) pair this with The Art of Debugging.

Core principles

  • Reach for the standard library first. A third-party package is only suggested when the stdlib genuinely falls short - and it's flagged with pip install.
  • Prefer the modern idiom. f-strings over %/.format(), pathlib over os.path, subprocess.run over os.system, dataclasses over ad-hoc tuples, logging over print in real programs.
  • Know the gotcha before it bites. Mutable default arguments, shallow vs deep copy, pass-by-object-reference, naive vs aware datetimes, the GIL - each chapter flags the trap.
  • Read the linked section before applying a recipe - each has worked examples, caveats, and edge cases the one-liner here omits.

Part I - Language core

Full chapters: Strings · Formatting · Numbers · Regex.

Part I - Data structures

Full chapters: Lists · Tuples · Sets · Dictionaries · Comprehensions/itertools.

Part I - Functions, classes, time

Full chapters: Functions · Classes · Dates.

Part II - Runtime & environment

Full chapters: Modules · Files/IO · Env & args · Subprocess.

Part II - Data, concurrency, network

Full chapters: Serialization · Concurrency · Networking.

Part III - Debugging, profiling & testing

Full chapters: Logging · Debugging · Introspection · Profiling · Exceptions · Testing.

Part IV - Packaging & tooling

Full chapters: Versions/Deps · Packaging · Code quality · Big data · Appendix.

Pick the recipe by need

NeedReach for
Format a number/string cleanlyformat spec mini-language, f-string tricks
Match/extract/replace textRegular Expressions
Count / group / default valuesCounter, defaultdict
Structured record typedataclasses
Stream/lazily process datagenerators & itertools
Work with files/pathspathlib
Parse CLI argumentsargparse
Run an external commandsubprocess.run
Read/write JSON/CSV/gzipSerialization
Parallelize workconcurrent.futures (mind the GIL)
Real logging (not print)logging
Code is too slowcProfile/timeit/line_profiler
Memory keeps growingtracemalloc/psutil
A stuck/crashed processget a traceback out of it
Write/run testspytest & unittest
Compare version stringscompare versions correctly
Package/pin a projectpyproject.toml, requirements

Notes for AI agents

  • Prefer the stdlib and the modern idiom (f-strings, pathlib, subprocess.run, dataclasses, logging) unless the user's environment dictates otherwise; only add a dependency when the stdlib truly can't do it.
  • Watch the flagged gotchas - mutable default args, shallow vs deep copy, pass-by-object-reference, naive datetimes, shell=True, bare except, string version comparison - before shipping a snippet.
  • Measure before optimizing: profile with cProfile/timeit/tracemalloc rather than guessing which line is slow or leaky.
  • Read the linked chapter section before applying an unfamiliar recipe - each has worked examples, caveats, and copy-paste code the index line omits.
  • Note the target version (3.8+ baseline); guard newer-only features (| dict merge, str.removeprefix, zoneinfo, structural pattern matching) when portability matters.
  • For deep runtime debugging of a crash/hang/segfault/OOM (gdb, strace, py-spy, core files, CUDA), use the companion skill: The Art of Debugging.