Python generators for database result sets
17th June 2003
I’ve read several articles on Python generators now, and I had almost got my head around them, but then I read this: Iterators and Databases by Andy Todd, which demonstrates a simple but intuitive way of using generators to iterate through rows from a database query without having to load all of the rows in to a list in memory first. Brilliant.
Andy links to this article which includes a nice one line summary of why generators exist (generators return iterators):
The motivation behind iterators is twofold. Working with data as sequences is often the most straightforward approach, and a sequence that is processed in linear order often does not need to actually exist all at once.
More on generators:
- Charming Python: Iterators and simple generators is a good introductory tutorial
- PEP 255: Simple Generators is the PEP that formally describes the language feature
More recent articles
- Qwen2.5-Coder-32B is an LLM that can code well that runs on my Mac - 12th November 2024
- Visualizing local election results with Datasette, Observable and MapLibre GL - 9th November 2024
- Project: VERDAD - tracking misinformation in radio broadcasts using Gemini 1.5 - 7th November 2024