Problem / Solution Reference
Quick lookup for common Python tasks mapped to idiomatic, production-ready solutions for Python 3.14.
Recipe
Ctrl+F your problem. Copy the solution. Adapt names to your project.
When to reach for this:
- "How do I do X in Python?" moments during implementation
- Code review standardization
- Onboarding quick reference
Problem / Solution Table
| 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 |
Working Example
"""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:
- Pydantic for config, httpx for HTTP, lru_cache for deduplication
- pathlib for file I/O, logging with extras
- Patterns from the reference table composed together
Gotchas
- Using outdated idioms -
os.pathover pathlib,%formatting over f-strings. Fix: prefer right column solutions. - Copy-paste without context - async sync mismatch. Fix: match solution to your sync/async context.
- No error handling - examples are minimal. Fix: add try/except and timeouts in production.
- lru_cache on unhashable args - TypeError. Fix: hashable arguments only or custom cache key.
- requests library for new code - httpx preferred for sync and async parity. Fix: standardize on httpx.
Alternatives
| 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 |
FAQs
pathlib or os.path?
pathlib for all new code. os.path only for legacy compatibility.
requests or httpx?
httpx for new projects. Supports sync and async with same API.
dataclass or Pydantic?
dataclass for internal data. Pydantic for validation boundaries.
How do I contribute new entries?
Propose additions in team style guide when a pattern repeats in review.
Are these Python 3.14 specific?
Most work on 3.13+. Match patterns use 3.9+ dict merge syntax.
Sync vs async column?
Use async column in FastAPI/asyncio apps. Sync for scripts and blocking CLIs.
pandas or Polars for CSV?
Polars for performance. pandas for ecosystem compatibility.
How do I handle retries?
tenacity library with exponential backoff and jitter.
Testing these patterns?
Each pattern is unit-testable. See linked pytest articles.
Where is the full stdlib?
docs.python.org/3/library/ - this page is the curated shortcut.
Related
- 50 Python Rules - principles behind solutions
- PEP 8 & Style Reference - style conventions
- Python Fundamentals - language basics
- Standard Library Overview - stdlib map
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+.