Backporting from Python 2.3 to Python 2.2
9th June 2004
We have a home-grown templating system at work, which I intend to dedicate an entry to some time in the future. We originally wrote it in Python 2.2, but upgraded to Python 2.3 a while ago and have since been evolving our code in that environment. Today I found a need to load the most recent version of our templating system on to a small, long neglected application that had been running the original version ever since it had enough features to be usable.
Unfortunately, this application was running on a server that only had Python 2.2. Installing Python 2.3 would have been somewhat more painful here than on other servers we run for reasons I won’t go in to, so I decided to have a go at getting our current code to run under the older Python version.
In the end, I only had to make three minor changes, all at the top of the file in question.
I added
from __future__ import generators
as the very first line of the file. We use generators (with theyield
statement) in a few places—this feature was only properly added in Python 2.3, but was made available in Python 2.2 as a “future enhancement” through the aforementioned obscure import.I added
True, False = 1, 0
on the next line down. Surprisingly, Python 2.2 had no support for a boolean type and instead used a test for non-zero. The above line defines constants that behave enough like Python 2.3’s True and False to avoid any problems.I defined an
enumerate
function, which was introduced for real in Python 2.3. Here’s the code I used:def enumerate(obj): for i, item in zip(range(len(obj)), obj): yield i, item
All in all it only took around ten minutes to put the above together, after which the script worked just fine. It was interesting to see how our code had grown to rely on Python 2.3 features without us realising it.
Update: Check this entry’s comments for improvements to the above code snippets.
More recent articles
- Weeknotes: datasette-enrichments, datasette-comments, sqlite-chronicle - 8th December 2023
- Datasette Enrichments: a new plugin framework for augmenting your data - 1st December 2023
- llamafile is the new best way to run a LLM on your own computer - 29th November 2023
- Prompt injection explained, November 2023 edition - 27th November 2023
- I'm on the Newsroom Robots podcast, with thoughts on the OpenAI board - 25th November 2023
- Weeknotes: DevDay, GitHub Universe, OpenAI chaos - 22nd November 2023
- Deciphering clues in a news article to understand how it was reported - 22nd November 2023
- Exploring GPTs: ChatGPT in a trench coat? - 15th November 2023
- Financial sustainability for open source projects at GitHub Universe - 10th November 2023
- ospeak: a CLI tool for speaking text in the terminal via OpenAI - 7th November 2023