S
Steven D'Aprano
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?
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?