Skip to content

#Python

47 posts tagged Python. All posts

  1. AI & dataImproving search results with a cross-encoder rerankerAdd a cross-encoder reranking step to embedding or BM25 retrieval with sentence-transformers, measure what it gains on real queries, and what it costs in latency.
  2. PythonBuilding a command-line tool in Python with TyperBuild a small to-do CLI with Typer: commands, arguments and options with Annotated, a subcommand group, Rich tables, CliRunner tests and a pyproject entry point.
  3. AI & dataProcessing thousands of prompts with the Claude Message Batches APIWhen the Message Batches API fits, and a script that submits a batch with custom IDs, polls it, reads the results and resubmits errored or expired requests.
  4. PythonPython's sqlite3 module: row factories, transactions, WAL and adaptersPractical sqlite3 for Python 3.12+: sqlite3.Row, what with conn really does, the autocommit attribute, executemany, WAL mode, date adapters and threads.
  5. PythonIdempotent ETL jobs: watermarks, upserts and safe rerunsBuild an incremental extract-and-load job that can run twice without harm: high-watermarks, an overlap window for late rows, SQLite upserts and run ids.
  6. AI & dataHandling LLM API rate limits: retries, backoff and concurrency capsTell 429s from 529s and 5xx errors, use the Anthropic SDK's built-in retries, add backoff with jitter, and cap concurrency and input tokens with asyncio.
  7. PythonTracing a Python Web Service with OpenTelemetry and JaegerSet up the OpenTelemetry SDK in a FastAPI app, add manual spans, attributes and events, export over OTLP, and look at the traces in Jaeger running in Docker.
  8. PythonFree-threaded Python 3.14: running threads without the GILWhat PEP 703 and PEP 779 changed, how to install the 3.14t build, check whether the GIL is on, time a CPU-bound threading example, and avoid extension pitfalls.
  9. InvestingComputing CAGR, volatility, Sharpe ratio and max drawdown in PythonCompute CAGR, annualised volatility, the Sharpe ratio and maximum drawdown from daily prices with pandas, and avoid the annualisation and return-type mistakes.
  10. PythonChange data capture in Postgres with logical replication slotsStream inserts, updates and deletes out of Postgres: wal_level=logical, slots with test_decoding and pgoutput, REPLICA IDENTITY, publications, and a Python consumer.
  11. AI & dataSemantic search in Postgres with pgvectorStore embeddings in Postgres with pgvector: vector columns, distance operators, HNSW and IVFFlat indexes, and filtered queries that still return enough rows.
  12. PythonLinting and formatting Python with RuffConfigure Ruff in pyproject.toml, pick rule sets (E, F, I, UP, B), apply safe and unsafe fixes, compare ruff format with Black, and run both checks in CI.
  13. PythonProperty-based testing in Python with HypothesisProperty-based tests with Hypothesis and pytest: strategies, @given, a real bug in a run-length encoder, shrinking, @example, settings and the example database.
  14. Pythondbt Core with DuckDB: models, tests and incremental tablesBuild a small dbt project on DuckDB: the dbt-duckdb profile, CSV sources, staging and mart models with ref, generic data tests, an incremental model and dbt build.
  15. AI & dataRunning local LLMs with Ollama and calling them from PythonInstall Ollama, pull and run open models, call them over the REST API, the ollama Python package and the OpenAI-compatible endpoint, and size context and memory.
  16. PythonPython logging setup: dictConfig, JSON log lines and per-library levelsConfigure Python logging with dictConfig: the logger hierarchy, a small JSON formatter, quieter third-party libraries, logging.exception, and library rules.
  17. InvestingPulling company fundamentals from the SEC's XBRL company facts APIFetch revenue and net income for US-listed companies from data.sec.gov: CIK lookup, companyfacts and companyconcept, us-gaap tags, and deduplicating 10-K facts.
  18. AI & dataChunking documents for retrieval: fixed size, recursive splits and headingsFour ways to chunk documents for RAG, from fixed windows to heading-aware splits, plus a small recall test that shows which one works for your embedding model.
  19. Pythoncontextlib patterns in Python: contextmanager, ExitStack, suppress and chdirWrite context managers with @contextmanager, handle exceptions in them, manage many resources with ExitStack, and use suppress, chdir and async versions.
  20. AI & dataValidating DataFrames with Pandera schemasDeclare pandas DataFrame schemas as Pandera DataFrameModel classes: Field checks, custom checks, dtype coercion, lazy error reports and validation at pipeline boundaries.
  21. AI & dataCutting LLM costs with prompt caching in the Claude APIHow prefix caching works, where to put cache_control breakpoints, minimum lengths and TTLs, and how to read the cache usage fields to confirm you are getting hits.
  22. PythonCaching in Python with functools.cache, lru_cache and cached_propertyMemoise functions with functools.cache and lru_cache, cache per instance with cached_property, avoid the method-caching leak, and add TTLs with cachetools.
  23. RustWriting a Python extension in Rust with PyO3 0.28 and maturinBuild a Python module in Rust with PyO3 0.28 and maturin: #[pyfunction], a declarative #[pymodule], the Bound API, py.detach for threads, and wheels.
  24. AI & dataBuilding an MCP server in Python with FastMCPWrite a Model Context Protocol server with the official Python SDK: tools, resources and prompts over stdio, tested with the Inspector and added to Claude Code.
  25. PythonPython typing with Protocols and the PEP 695 generic syntaxStructural typing with typing.Protocol, the limits of runtime_checkable, Python 3.12's generic syntax and type statement, checked with mypy and Pyright.
  26. PythonHow Parquet files work: row groups, column chunks and statisticsWhat is inside a Parquet file: row groups, column chunks, pages, min/max statistics and predicate pushdown, codecs and encodings, inspected with pyarrow.parquet.
  27. InvestingA portfolio rebalancing calculator in PythonWrite a rebalancing calculator in plain Python: target weights, drift, rebalance bands, putting new cash to work before selling, and rounding to whole shares.
  28. AI & dataA small eval runner for LLM features in PythonBuild a 160-line eval runner for an LLM feature: JSONL test cases, exact, regex and LLM-as-judge graders, concurrent runs and scores tracked per prompt version.
  29. PythonManaging Python projects with uv: lockfiles, tools and inline script metadataRun a Python project with uv from init to lockfile, use uvx for CLI tools, install Python versions, and give single-file scripts their own dependencies.
  30. AI & dataPolars for pandas users: expressions, lazy frames and group_byThe same DataFrame transformations in pandas and Polars side by side: pl.col expressions, with_columns, group_by().agg, window functions, lazy scan_csv and no index.
  31. AI & dataWriting a tool-use loop for the Claude API by handBuild the tool-calling loop for Claude yourself in Python: JSON Schema tools, the stop_reason loop, tool_result blocks, errors with is_error and a turn limit.
  32. Pythonasyncio TaskGroup and asyncio.timeout: structured concurrency in PythonReplace asyncio.gather with TaskGroup, handle failures with ExceptionGroup and except*, add deadlines with asyncio.timeout, and cap concurrency.
  33. AI & dataRetrieval-augmented generation from scratch with SQLiteBuild RAG in about 130 lines of Python: chunk Markdown, embed it locally, store vectors in SQLite, search by cosine similarity and get cited answers from Claude.
  34. Pythondataclasses, attrs or Pydantic: picking a Python data class libraryThe same order model written with dataclasses, attrs and Pydantic: frozen objects, slots, defaults, validation, conversion and JSON, and when to use each.
  35. InvestingBacktesting a moving-average crossover in pandas without look-ahead biasA vectorised pandas backtest of a 50/200-day crossover: signals on the close, trades on the next bar, transaction costs, and why one price series proves nothing.
  36. AI & dataQuerying CSV and Parquet files with DuckDBUse DuckDB's CLI and Python API to query CSV and Parquet files in place, read many files with globs, write partitioned Parquet, and run SQL on pandas DataFrames.
  37. AI & dataGetting reliable JSON from an LLM: schemas, structured outputs and validationThree ways to get JSON out of Claude in Python: prompting, a forced tool call and the structured outputs beta, with Pydantic validation, retries and stop reasons.
  38. PythonStructural pattern matching in Python: matching dicts, sequences and classesUse match/case to parse JSON events and command tuples, match classes with __match_args__, add guards, and avoid the capture-vs-constant trap.
  39. PythonDecrypting Laravel Crypt::encryptString values in PythonHow Laravel's encrypter builds its AES-256-CBC payload and HMAC-SHA256 MAC, and a Python function using pycryptodome that verifies and decrypts it.
  40. PythonScraping a free proxy list and rotating proxies with Python requestsWhy scrapers use proxies, how to pull IP:port pairs from a proxy list page with requests and BeautifulSoup, check which ones work, and rotate them.
  41. PythonCalling SOAP APIs from Python with ZeepHow to call a SOAP web service from Python with Zeep: inspect a WSDL, call operations, build complex types, handle faults and log the raw XML.
  42. PythonExclude live-server tests by default with pytest markers and fixturesTag tests that hit a live server with a custom pytest marker, skip them by default, and opt in with -m or an environment variable.
  43. PythonWriting temporary files in Azure Functions with Python's tempfileWhy writes to your Azure Functions app folder fail, where you can write instead, and how to use Python's tempfile module to handle files safely in a function.
  44. PythonHandling file uploads in FastAPI, Django and FlaskMinimal, working file upload endpoints in FastAPI, Django and Flask: what to install, how to save the file safely, and how to cap upload size.
  45. AI & dataRunning OCRmyPDF in a containerized Azure FunctionPackage OCRmyPDF, Tesseract and Ghostscript into a custom Azure Functions container and expose an HTTP endpoint that OCRs an uploaded PDF and returns its text.
  46. PythonSign in to the Wagtail admin with Microsoft Entra ID (Azure AD)Add Microsoft Entra ID (formerly Azure Active Directory) login to the Wagtail admin with social-auth-app-django, including settings, URLs and a login button.
  47. AI & dataLessons from scraping construction permits and bid sitesWhat I learned scraping permit reports, open data and bid-opportunity sites for YellowSheet, plus a small C# scraper at CSPS.

© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)