Skip to content

Python

Scripting, web frameworks, testing and data work. 103 posts, newest first. All topics

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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.
  18. 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.
  19. 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.
  20. PythonBuild 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.
  21. PythonFastAPI 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.
  22. PythonTensorFlow 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.
  23. PythonPython 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.
  24. PythonGetting 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.
  25. PythonPyTorch 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.
  26. PythonGetting 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.
  27. PythonMaking 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.
  28. PythonPyCharm 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.
  29. PythonExtracting 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.
  30. PythonProtocol 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.
  31. PythonPersonal 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.
  32. PythonCutting 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.
  33. PythonApache 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.
  34. PythonPackaging 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.
  35. PythonTranscribing 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.
  36. PythonChapter 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.
  37. PythonChapter 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.
  38. PythonChapter 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.
  39. PythonChapter 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.
  40. PythonWriting 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.
  41. PythonAutomating 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.
  42. PythonChapter 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.
  43. PythonChapter 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__.
  44. PythonChapter 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.
  45. PythonBuild 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.
  46. PythonExoPlayer 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.
  47. PythonRunning 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.
  48. PythonServing 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.
  49. PythonUsing 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.
  50. PythonC++ 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.
  51. PythonScraping 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.
  52. PythonBuilding 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.
  53. PythonFlask-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.
  54. PythonWhy 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.
  55. PythonMeasuring 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.
  56. PythonUsing 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.
  57. PythonShowing 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.
  58. PythonServe 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.
  59. PythonGetting 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.
  60. PythonGenerating 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.
  61. PythonScikit-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.
  62. 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.
  63. PythonImage 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.
  64. PythonFinding 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.
  65. 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.
  66. PythonMatplotlib 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.
  67. 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.
  68. 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.
  69. PythonScraping 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.
  70. 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.
  71. 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.
  72. PythonWeb 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.
  73. PythonGetting 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.
  74. PythonIntroduction 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.
  75. PythonApache 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.
  76. PythonDownloading 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.
  77. PythonConverting 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.
  78. PythonOpenCV 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.
  79. PythonPyPDF2 (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.
  80. PythonGetting 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.
  81. PythonScraping 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.
  82. PythonTalking 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.
  83. PythonSQLAlchemy 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.
  84. PythonCelery 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.
  85. PythonGenerating 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.
  86. PythonBuild 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.
  87. Pythonpython-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.
  88. PythonCombining 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.
  89. PythonSigning 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.
  90. PythonManaging 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.
  91. PythonGetting 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.
  92. PythonPygame 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.
  93. PythonWhat 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.
  94. PythonNumPy 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.
  95. PythonPython 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.
  96. PythonTortoise 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.
  97. PythonBuild 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.
  98. PythonScraping 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.
  99. PythonChecking 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.
  100. PythonGetting 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.
  101. PythonSimple deta micro to show my deta drive filesLeveraging fastapi to show stock report files
  102. PythonThoughts on dash v2.5.0After updating a project to dash v2.5.0
  103. PythonWhat 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)