Python
Scripting, web frameworks, testing and data work. 103 posts, newest first. All topics
Building 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.
Python'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.
Idempotent 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.
Tracing 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.
Free-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.
Change 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.
Linting 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.
Property-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.
dbt 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.
Python 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.
contextlib 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.
Caching 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.
Python 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.
How 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.
Managing 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.
asyncio 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.
dataclasses, 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.
Structural 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.
Decrypting 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.
Build a command-line contact book in Python with SQLiteA small menu-driven CLI that adds, lists, updates and deletes contacts in a SQLite database, using only Python's standard library.
FastAPI basics: routes, validation, and dependencies in PythonBuild a small FastAPI app in Python, covering path and query parameters, Pydantic request validation, and dependencies with yield for resource cleanup.
TensorFlow in Python: train, save and serve an MNIST classifier with KerasTrain an MNIST digit classifier with TensorFlow and Keras in Python: load data with tf.data, build, train and evaluate a model, save it, and serve it.
Python Levenshtein: edit distance and string similarity in PythonHow to install the Levenshtein package (formerly python-Levenshtein) and use distance, ratio, Jaro-Winkler and editops to compare strings in Python.
Getting started with Flask: routes, JSON and the dev serverInstall Flask 3, write a small app with HTML and JSON routes, run it with the flask CLI, and see which extensions add databases, forms and logins.
PyTorch basics: tensors, autograd and a first training loopPyTorch basics in one sitting. Create tensors, compute gradients with autograd, define an nn.Module, and train a small network with a standard training loop.
Getting started with Pygame: a game loop, input and spritesInstall Pygame, set up a game loop with a fixed frame rate, handle keyboard input, and move a sprite around the screen, in one runnable script.
Making HTTP requests in Python with RequestsHow to make HTTP requests in Python with Requests: GET and POST, query parameters, file uploads and downloads, timeouts, errors, auth and redirects.
PyCharm for Python: project setup, refactoring, debugging and GitSet up a PyCharm project with a virtual environment, then use its code completion, refactoring shortcuts, debugger and Git tools in daily Python work.
Extracting text from a PDF in Python with pypdfA small command-line script that uses pypdf (the successor to PyPDF2) to write the text of every page in a PDF to a text file, including encrypted PDFs.
Protocol Buffers in Python: schemas, code generation and schema evolutionHow Protocol Buffers work: define a .proto schema, generate Python code with protoc, serialize and parse messages, and evolve the schema safely.
Personal finance checklist: retirement, insurance, credit, taxes and side incomeA US-focused checklist for retirement income, insurance, credit, taxes and side-hustle income, with the rules of thumb and the official sources behind them.
Cutting voice clips from YouTube videos with yt-dlp and ffmpegA Python script that downloads a YouTube video's audio with yt-dlp and cuts it into short WAV clips with ffmpeg, for use as Tortoise TTS voice samples.
Apache Thrift: a Java server and Python client from one IDL fileDefine a service in Thrift IDL, generate Java and Python code, and call a Java Thrift server from a Python client, with notes on protocols and versions.
Packaging Python scripts as standalone executables with PyInstallerPackage a Python script into a standalone executable with PyInstaller, set an icon, hide the console, bundle data files and fix common build problems.
Transcribing and subtitling YouTube videos with Whisper, yt-dlp and GradioA Gradio app that downloads a YouTube video with yt-dlp, transcribes or translates it with OpenAI Whisper, writes an SRT file, and burns the subtitles in with ffmpeg.
Chapter 10: Introduction to data science in PythonWhat data science is, how it differs from data analytics, and three starter examples using matplotlib, pandas, and requests.
Chapter 7: Reading, writing and processing files in PythonOpening files with open() and with, file modes, processing lines with string methods and regex, CSV/JSON/XML modules, large files, and running ffmpeg.
Chapter 8: Functional programming in PythonChapter 8 of my intro to Python book covers pure functions, map, filter, reduce, lambdas, comprehensions and generators, with runnable examples.
Chapter 9: Web development with Python and FlaskChapter 9 of my intro to Python book covers HTTP, HTML, CSS and JavaScript basics, Python web frameworks, a small Flask app with a form, and running it in Docker.
Writing generator functions with yield in PythonHow the yield keyword turns a function into a generator, how to consume one with a for loop or next(), and when generators save memory.
Automating mouse and keyboard input in Python with PyAutoGUIControl the mouse and keyboard from Python with PyAutoGUI: moving, clicking, typing, hotkeys, screenshots and image matching, plus a Notepad script.
Chapter 4: Python modules, packages and pipHow to import modules, use the standard library, write your own modules and packages, and install third-party packages with pip.
Chapter 5: Classes and objects in PythonHow to define a Python class, create objects from it, use self and __init__, access attributes and methods, and give objects a readable __str__.
Chapter 6: Handling and raising exceptions in PythonHow Python exceptions work, catching them with try/except/else/finally, raising your own with raise and assert, and defining custom exception classes.
Build a simple URL shortener in Python with Flask and SQLiteA single-file Flask app that turns long URLs into six-character codes, stores them in SQLite, and redirects visitors to the original address.
ExoPlayer on Android: playing video and DASH streams with Media3How ExoPlayer is structured and how to play a video or DASH stream with it in an Android app, using the current AndroidX Media3 artifacts.
Running remote commands over SSH with Python FabricUse Fabric to run commands on remote servers over SSH: Connection objects in a script, sudo, file transfers, and fab tasks run from the command line.
Serving a Python web app with Gunicorn and NginxHow to serve a Flask (or any WSGI) app with Gunicorn, set workers, bind address and timeouts in gunicorn.conf.py, and put Nginx in front of it.
Using Redis from Python with redis-py: data types, expiry and pub/subConnect to Redis from Python with redis-py and work with strings, hashes, lists, sets, sorted sets, key expiry and pub/sub messaging.
C++ interoperability with C, Python and Java: extern "C", pybind11, JNI and SWIGHow to call C++ from C, Python and Java using extern "C" wrappers, ctypes, pybind11, JNI, JNA, SWIG and Java's Foreign Function and Memory API.
Scraping HTML tables with pandas and Beautiful SoupPull an HTML table into a pandas DataFrame with read_html, parse it by hand with Beautiful Soup when that fails, then clean it and save it as CSV.
Building a PyQt6 app to edit a YAML fileA small PyQt6 window that loads a YAML post config, lets you edit its title, tags, description and sections, and saves it back to disk.
Flask-RESTful: a CRUD API with Resource classesBuild a small CRUD API for tasks with Flask-RESTful: Resource classes, URL routing, status codes, and testing each endpoint with curl.
Why my blog post generator uses ChatGPT instead of EdgeGPT (Bing Chat)Notes from porting my ChatGPT blog post generator to EdgeGPT (Bing Chat), including how to strip Bing's citation markers from responses.
Measuring how much of an image each detected object covers with YOLOv3 and OpenCVDetect objects in an image with YOLOv3 and OpenCV's DNN module, then report each bounding box's area as a fraction of the whole image.
Using IPython as a calculator to work out progressive income taxUse the IPython shell for quick arithmetic, then write a small function that calculates tax across progressive brackets and check the result.
Showing commodity and bond tables in Streamlit with OpenBBA small Streamlit app that showed commodity and bond tables from OpenBB Terminal, plus a version rewritten for the current OpenBB Platform API.
Serve FastAPI over HTTPS on a Google Compute Engine subdomain with ApachePoint a subdomain at a Compute Engine VM, run FastAPI behind an Apache reverse proxy, and add a free Let's Encrypt certificate with Certbot.
Getting started with pytest: tests, fixtures and parametrizeWrite and run Python tests with pytest, read its assertion output, and use fixtures, parametrize, pytest.raises and tmp_path with runnable examples.
Generating descriptions and keywords for LaTeX diagrams with ChatGPTA Python script that walks a folder of LaTeX diagram sources and asks ChatGPT to write a description and a keyword list for each file.
Scikit-learn basics: training and evaluating a classifier in PythonTrain and evaluate a k-nearest neighbours classifier on the Iris dataset with scikit-learn, then use a pipeline and cross-validation for a more honest score.
Scraping 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.
Image processing in Python with Pillow: resize, rotate, filter and EXIFOpen, convert and save images with Pillow, then resize, rotate, flip, blur, adjust brightness and contrast, and read EXIF metadata.
Finding new YouTube videos of interest with the YouTube Data API in PythonHow my media_nlp script polls YouTube channels for new uploads, flags videos whose titles match keywords, and emails a summary table with Jinja and Mailjet.
Calling 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.
Matplotlib basics: line, scatter, bar, 3D and animated plotsMake line, scatter, bar, histogram, 3D and animated plots with Matplotlib's object-oriented API, then label, combine and save them.
Exclude 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.
Writing 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.
Scraping Super Bowl winners from ESPN with pandasUse pandas.read_html to pull ESPN's Super Bowl winners, MVPs and touchdown leaders tables, clean the headers, and plot how often each stadium hosted.
Handling 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.
Sign 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.
Web scraping with Beautiful Soup: extract headings and tables from a Wikipedia pageFetch a Wikipedia page with Requests and pull out its title, section headings, first paragraph and infobox using Beautiful Soup's find, find_all and select.
Getting started with Jupyter notebooks: install, run cells, avoid hidden stateWhat a Jupyter notebook is, how to install and launch JupyterLab with pip, how cells and kernels work, and the common pitfalls of notebook-based work.
Introduction to Python: where it came from, what it's used for, lists and argparseA short introduction to Python's origins and common uses, followed by two first examples, working with lists and parsing command-line arguments with argparse.
Apache Spark basics: how it runs jobs, its libraries, and a PySpark exampleHow Apache Spark runs jobs across a cluster (driver, executors, stages, lazy evaluation), what its libraries do, and a PySpark word count you can run locally.
Downloading CSE company filings with Python and posting them to DiscordA Python script that uses cad_tickers to find new documents for CSE-listed stocks, saves the PDFs, and posts each one to a Discord webhook.
Converting PDFs to PNGs with ImageMagick from PythonA Python script that converts every PDF in a folder to PNG images by calling ImageMagick with subprocess, plus the Ghostscript and policy gotchas.
OpenCV in Python: reading images, basic transforms, edges and face detectionLoad, display and save images with OpenCV in Python, then resize, rotate, threshold, blur, find edges and detect faces with a Haar cascade.
PyPDF2 (now pypdf): reading, merging and watermarking PDFs in PythonRead, extract text from, merge, watermark and encrypt PDFs in Python. PyPDF2 is now pypdf, so the examples use the current pypdf API.
Getting started with Django: models, views, URLs and templatesBuild a small Django app from scratch: create a project and app, define a model, run migrations, and render it with a view, URLs, a template and static files.
Scraping Indeed job listings with BeautifulSoup and pandas (no longer works)My old Indeed scraper, which pulled job listings into pandas, tagged skills and degrees with regex, and emailed charts via Mailjet, until Cloudflare blocked it.
Talking to serial devices from Python with PySerialOpen a serial port with PySerial, read and write bytes, set timeouts and line settings, handle incoming lines on a background thread, and read sensor data from an Arduino.
SQLAlchemy 2.x ORM basics: models, sessions and queries in PythonDefine models, create tables, and insert, query, update and delete rows with the SQLAlchemy 2.x ORM, plus relationships, transactions and inheritance.
Celery in Python: background tasks, retries, routing and monitoringSet up Celery with Redis, define and call tasks, add retries, route tasks to queues and set priorities, and monitor workers with the CLI and Flower.
Generating blog post drafts from a YAML config with ChatGPT and Stable DiffusionA Python script that reads a YAML config, asks ChatGPT for each section, writes Markdown with frontmatter, and generates a header image.
Build a tkinter weather app in Python with the OpenWeatherMap APICall the OpenWeatherMap geocoding and current-weather APIs with requests, handle errors, and show temperature, humidity and conditions in a small tkinter window.
python-telegram-bot: build an echo bot with commandsBuild a working Telegram echo bot with python-telegram-bot v22, using its asyncio Application API, command handlers and message filters.
Combining a Cantonese dub with an English-subtitled video using Python and ffmpegHow I grabbed a Cantonese dub with Selenium and yt-dlp, checked it against an English-subbed copy with ffprobe, and merged the two with ffmpeg.
Signing and verifying JSON Web Tokens in Python with PyJWTHow a JSON Web Token is structured, and how to sign, verify and expire JWTs in Python with PyJWT 2.x, including which exceptions to catch.
Managing Python environments with Anaconda and condaCreate, share and remove isolated Python environments with conda, install packages with conda and pip, and avoid Anaconda's licensing trap.
Getting started with Jupyter Notebook for PythonInstall and launch Jupyter Notebook, work with code and Markdown cells, use IPython magics, plot inline with Matplotlib, and export or share notebooks.
Pygame Zero: build a simple space shooter in PythonBuild a small space shooter with Pygame Zero: actors, keyboard input, shooting, collisions, a score and a game-over screen, in about 70 lines of Python.
What changed in PyCaret 3.0.0A summary of the PyCaret 3.0.0 release, covering the time series module, the new object-oriented API, pipeline-based preprocessing and breaking changes.
NumPy basics: arrays, broadcasting and vectorised maths in PythonNumPy essentials: creating and reshaping arrays, vectorised arithmetic, broadcasting, indexing, aggregations, linear algebra and random numbers with Generator.
Python argparse basics: positional arguments, flags and a small CLIHow to define positional arguments and flags with Python's argparse module, with a sum/max example and a small book-tracker CLI that saves to JSON.
Tortoise TTS: how it works and how to generate speech in a cloned voiceHow the Tortoise text-to-speech model turns text and a few reference clips into speech, and how to run it from the command line or Python.
Build a password generator in Python with secrets and tkinterGenerate random passwords with Python's secrets module, then wrap the generator in a small tkinter window with a length field and a button.
Scraping Flipp grocery flyers with Python and SeleniumHow flipp_flyer_parser drives Chrome through the Flipp flyer iframes on Walmart, Save-On-Foods, Superstore and Loblaws, and pulls prices into JSON and PostgreSQL.
Checking whether a YouTube channel is live with Selenium and BeautifulSoupA Python script that loads a YouTube channel page in a remote Selenium browser and parses the HTML to tell whether its latest stream is live or upcoming.
Getting started with OpenCV in Python by building a cartoon filterInstall OpenCV for Python, see which beginner projects it suits, and build a working cartoon filter from blurring, adaptive thresholding and a bilateral filter.
Simple deta micro to show my deta drive filesLeveraging fastapi to show stock report files
Thoughts on dash v2.5.0After updating a project to dash v2.5.0
What I did when open source library changed to semi open sourceHere I explain what my actions when an open source library got taken down from github.
© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)