Writing backwards compatible code

Jack Diederich jack at performancedrivers.com
Fri Apr 14 14:59:39 EDT 2006


On Sat, Apr 15, 2006 at 04:04:44AM +1000, Steven D'Aprano wrote:
> I came across an interesting (as in the Chinese curse) problem today. I
> had to modify a piece of code using generator expressions written with
> Python 2.4 in mind to run under version 2.3, but I wanted the code to
> continue to use the generator expression if possible.
> 
> My first approach was to use a try...except block to test for generator
> expressions:
> 
> try:
>     gen = (something for x in blah)
> except SyntaxError:
>     def g():
>         for x in blah:
>             yield something
>     gen = g()
> 
> The solution which worked was to put the generator expression in a second
> module, then import that:
> 
> try:
>     import othermodule
> except SyntaxError:
>     # fall back code
>
> What techniques do others use?
> 

If you want to support 2.3 just use the yield version.  Having
two versions of the same thing is asking for trouble.  Twice
the tests, twice the room for breakage, twice the places to
update if you want to change it.

-Jack




More information about the Python-list mailing list