python· 7 min read

Python idioms and tooling cheat sheet

Small patterns that make Python code shorter and clearer, and the tooling to keep projects isolated.

Virtual environments

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pip freeze > requirements.txt
deactivate

Running pip as python -m pip guarantees it installs into the interpreter you are actually using.

Comprehensions

squares = [n * n for n in range(10)]
evens   = [n for n in nums if n % 2 == 0]
by_id   = {user.id: user for user in users}
unique  = {word.lower() for word in words}
total   = sum(item.price for item in cart)   # generator, no list built

f-strings

name, score = "Ada", 0.9876
f"{name:>10}"        # right-align in 10 chars
f"{score:.2%}"       # '98.76%'
f"{1234567:,}"       # '1,234,567'
f"{score=}"          # 'score=0.9876' — handy for debugging

Files with pathlib

from pathlib import Path

root = Path(__file__).parent
config = root / "config" / "settings.toml"
text = config.read_text(encoding="utf-8")

for md in root.glob("**/*.md"):
    print(md.stem, md.stat().st_size)

Dataclasses

from dataclasses import dataclass, field

@dataclass(frozen=True)
class Note:
    title: str
    tags: list[str] = field(default_factory=list)
    draft: bool = False

n = Note("Git basics", ["git"])
print(n)   # Note(title='Git basics', tags=['git'], draft=False)

Standard library gems

ModuleUseful for
collections.CounterCounting items: Counter(words).most_common(3)
collections.defaultdictGrouping without key checks
itertoolschain, groupby, batched, pairwise
functools.cacheMemoising pure functions
enumerate / zipIndex + value, parallel iteration
json, csvReading and writing common formats