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
| Module | Useful for |
|---|---|
collections.Counter | Counting items: Counter(words).most_common(3) |
collections.defaultdict | Grouping without key checks |
itertools | chain, groupby, batched, pairwise |
functools.cache | Memoising pure functions |
enumerate / zip | Index + value, parallel iteration |
json, csv | Reading and writing common formats |