2006-09-20

Python 2.5 released

Python 2.5 has been released into the wild, now with more features! One of those new features are conditional expressions, similar to the ternary ?: -operator in C/C++ and some other languages. And to show a bad example of how useful a feature it is, here's a small snippet returning a float range generator utilizing anonymous generators, conditional expressions and lambda functions:

frange=lambda start, stop=0.0, step=1.0, include_stop=False:
(
(min if step > 0 else max)((start, stop)) + index*step
for index in xrange(int(abs(start - stop) / abs(step) + 1))
if index*step < (abs(start-stop) + (step if include_stop else 0))
)


Like the xrange() and range() functions, the generated sequence does not include the stop-value. However, since inclusive ranges are quite useful with floats, the default behaviour can be overridden by setting the include_stop argument to True. In this case the stop-value is included in the range if it is a multiple of steps from start.