python
star
bookmark_border
Load a JSON file and get a readable message when it is missing or malformed.
import json
from pathlib import Path
def load_json(path: str | Path) -> dict:
beginner
#json #files #errors
python
star
bookmark_border
A decorator that retries a function on chosen exceptions, waiting longer after each failure.
import functools
import random
import time
intermediate
#retry #decorators #network
python
bookmark_border
Memoize a pure function with functools.lru_cache.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n: int) -> int:
beginner
#performance #functools #recursion
python
bookmark_border
Use the secrets module (never random) for passwords, tokens and reset links.
import secrets
import string
reset_token = secrets.token_urlsafe(32) # for links: /reset/<token>
api_key = "pk_" + secrets.token_hex(24)
beginner
#security #secrets #auth
python
bookmark_border
Turn a flat list into a dict of lists with collections.defaultdict.
from collections import defaultdict
orders = [
{"customer": "ada", "total": 30},
{"customer": "linus", "total": 12},
beginner
#collections #dict #data
python
bookmark_border
Read rows as dicts and write a filtered copy with csv.DictWriter.
import csv
import io
source = io.StringIO("name,score\nada,91\nlinus,78\ngrace,88\n") # use open("in.csv") for a file
rows = [row for row in csv.DictReader(source) if int(row["score"]) >= 80]
beginner
#csv #files #data
python
bookmark_border
Turn any title into a lowercase, URL-safe slug.
import re
import unicodedata
def slugify(text: str) -> str:
beginner
#strings #regex #urls
python
bookmark_border
A tiny context manager that prints how long a block took.
import time
from contextlib import contextmanager
@contextmanager
intermediate
#performance #context-manager
python
bookmark_border
Use __post_init__ to reject bad values as soon as an object is created.
from dataclasses import dataclass, field
@dataclass
class Product:
intermediate
#dataclasses #validation #types