Writing backwards compatible code

James Stroud jstroud at ucla.edu
Fri Apr 14 20:29:37 EDT 2006


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()
> 
> 
> This failed to work under 2.3, because the SyntaxError occurs at compile
> time, and so the try block never happens.
> 
> I've been burnt by making assumptions before, so I tried a second,
> similar, approach:
> 
> if sys.version_info >= (2, 4):
>     gen = (something for x in blah)
> else:
>     # you know the rest
> 
> As expected, that failed too.
> 
> 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?
> 
> 

Here is one every one will have fun lambasting:

try:
   exec('gen = (something for x in blah)')
except:
   def g():
     # etc.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list