Problem / Solution Reference
Quick lookup for common Python tasks mapped to idiomatic, production-ready solutions for Python 3.14.
Search across all documentation pages
Quick lookup for common Python tasks mapped to idiomatic, production-ready solutions for Python 3.14.
Ctrl+F your problem. Copy the solution. Adapt names to your project.
When to reach for this:
| Problem | Idiomatic Solution |
|---|---|
| Read a file | Path("f.txt").read_text(encoding="utf-8") |
| Write a file | Path("f.txt").write_text(data, encoding="utf-8") |
| List files recursively | Path("dir").rglob("*.py") |
| HTTP GET request | httpx.get(url, timeout=30.0) |
| Async HTTP | async with httpx.AsyncClient() as c: await c.get(url) |
| Parse JSON | json.loads(text) or response.json() |
| Validate config | Pydantic BaseSettings or BaseModel |
| CLI tool | Typer or Click with [project.scripts] |
| Run tests | uv run pytest |
| Format code | uv run ruff format . |
| Lint code | uv run ruff check --fix . |
| Type check | uv run mypy src/ |
| Cache function results | @lru_cache(maxsize=128) |
| Parallel I/O | asyncio.gather(*tasks) |
| Parallel CPU | ProcessPoolExecutor |
| Safe temp file | tempfile.NamedTemporaryFile(delete=False) |
| Env var with default | os.environ.get("KEY", "default") |
| Log structured | logging.getLogger(__name__).info("msg", extra={...}) |
| Retry on failure | tenacity @retry or manual with backoff |
| Parse datetime | datetime.fromisoformat(s) or dateutil.parser |
| Unique items preserving order | list(dict.fromkeys(items)) |
| Flatten nested list | [x for sub in nested for x in sub] |
| Count occurrences | collections.Counter(items) |
| Group by key | itertools.groupby(sorted(items, key=k), key=k) or defaultdict |
| Merge dicts | {**d1, **d2} or d1 | d2 (3.9+) |
| Dataclass quickly | @dataclass(frozen=True, slots=True) |
| Enum constants | class Color(Enum): RED = "red" |
| Context manager | @contextmanager decorator |
| Subprocess safely | subprocess.run(cmd, check=True, capture_output=True) |
| Load .env | pydantic-settings with env_file=".env" |
| Test HTTP API | TestClient(app) (FastAPI) |
| Mock external call | @patch("mymodule.httpx.get") |
| Serialize dataclass | dataclasses.asdict(obj) |
| Deep copy | copy.deepcopy(obj) |
| Check type at runtime | isinstance(x, MyClass) not type(x) == MyClass |
| Sort dict by value | sorted(d.items(), key=lambda kv: kv[1]) |
| Read CSV | csv.DictReader(open("f.csv")) or polars.read_csv("f.csv") |
| Read parquet | polars.read_parquet("f.parquet") or pd.read_parquet |
| Generate UUID | uuid.uuid4() |
| Hash password | argon2.PasswordHasher().hash(password) |
| Secure token | secrets.token_urlsafe(32) |
| Parse URL | urllib.parse.urlparse(url) |
| Time a function | time.perf_counter() before/after |
| Profile CPU | cProfile.run("main()") |
| Install package | uv add package |
| Lock dependencies | uv lock && uv sync --frozen |
"""Common patterns combined in a realistic script."""
from __future__ import annotations
import logging
from functools import lru_cache
from pathlib import Path
import httpx
from pydantic import BaseModel
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
class Config(BaseModel):
api_url: str = "https://api.example.com"
cache_size: int = 128
@lru_cache(maxsize=128)
def fetch_status(base_url: str, service: str) -> dict:
with httpx.Client(base_url=base_url, timeout=10.0) as client:
r = client.get(f"/status/{service}")
r.raise_for_status()
return r.json()
def main() -> None:
config = Config()
for svc in ("billing", "auth", "notifications"):
data = fetch_status(config.api_url, svc)
log.info("service ok", extra={"service": svc, "status": data.get("status")})
out = Path("report.json")
out.write_text(str(fetch_status.cache_info()), encoding="utf-8")
if __name__ == "__main__":
main()What this demonstrates:
os.path over pathlib, % formatting over f-strings. Fix: prefer right column solutions.| Alternative | Use When | Don't Use When |
|---|---|---|
| Stack Overflow search | Novel problem | Common task listed here |
| stdlib docs | Edge case behavior | Quick idiom lookup |
| AI code gen | Boilerplate scaffolding | Security-critical patterns |
pathlib for all new code. os.path only for legacy compatibility.
httpx for new projects. Supports sync and async with same API.
dataclass for internal data. Pydantic for validation boundaries.
Propose additions in team style guide when a pattern repeats in review.
Most work on 3.13+. Match patterns use 3.9+ dict merge syntax.
Use async column in FastAPI/asyncio apps. Sync for scripts and blocking CLIs.
Polars for performance. pandas for ecosystem compatibility.
tenacity library with exponential backoff and jitter.
Each pattern is unit-testable. See linked pytest articles.
docs.python.org/3/library/ - this page is the curated shortcut.
Stack versions: This page was written for Python 3.14.0, FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026