Skip to content

Instantly share code, notes, and snippets.

View bbelderbos's full-sized avatar

Bob Belderbos bbelderbos

View GitHub Profile
@bbelderbos
bbelderbos / typed_settings.py
Created September 26, 2026 07:16
From X: One additional thing you can do with a Typed Settings-like object is set values to the results of external system calls. Think db, redis, S3, task queue, etc. All your external deps get exercised at app startup, so you know the whole system is ready to go.
# gemini generated example based on comment above
import redis
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import create_engine, text
class Settings(BaseSettings):
# --- 1. Basic Typed Settings (Fails fast if missing/invalid) ---
OPENAI_API_KEY: str = Field(..., description="Required API key")
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Protocol
@dataclass(frozen=True)
class Say:
text: str
from decimal import Decimal
from pydantic import BaseModel, ValidationError
class Expense(BaseModel):
amount: Decimal
# coercion: each valid input becomes a Decimal
for v in [5, 5.50, "5.50", Decimal("5.50")]:
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "python-telegram-bot>=21",
# "openai>=1.40",
# "httpx",
# "python-decouple",
# "pydantic",
# ]
# ///
"""Single-file Pyodide exercise starter.
Run:
python pyodide_starter.py
Writes index.html next to this file and serves it on http://localhost:8765.
Open the URL, hit "Run tests", and watch pytest run inside the browser
against a small stdlib Pybites Bite (anagrams). Edit the HTML to swap in
your own exercises.
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "anthropic>=0.40",
# "httpx>=0.27",
# "openai>=1.50",
# "python-decouple>=3.8",
# ]
# ///
# AI trend digest: fetch HN + Reddit concurrently, rank with an LLM, print markdown.
"""
Finite State Machine — GitHub PR workflow
Full implementation + tests from: https://belderbos.dev/blog/build-finite-state-machine-python
Run: uvx pytest fsm.py -v
"""
import pytest
# --- Implementation ---
import asyncio
import random
from datastar_py import ServerSentEventGenerator as SSE
from datastar_py.fastapi import DatastarResponse
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI(title="Datastar Stock Ticker")
# /// script
# dependencies = [
# "python-decouple",
# "requests",
# ]
# ///
import argparse
import json
import sys
# 1) Literal patterns: Cleanly dispatch on exact values (great for status codes and enums).
def handle_response(status: int) -> str:
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500: