Python 2.1 syntax to Python 1.5.2

Delaney, Timothy tdelaney at avaya.com
Sun Nov 4 18:30:30 EST 2001


> From: Sean 'Shaleh' Perry [mailto:shalehperry at home.com]
> On 02-Nov-2001 Stuart Bishop wrote:
> > Before I rewrite all my lovely list comprehensions and
> > 'print >>' statements into python 1.5 syntax, I don't suppose
> > anyone has code that automagically does the translation?
> > 
> 
> the list comprehension could be tricky, the print is fairly easy.

All list comprehensions should translate directly to a combination of map()
and filter() calls, unless you're doing something nasty like rebinding names
during the course of the comprehension.

def process (x):
    """"""
    return x**2

r = xrange(1000)
lc = [process(x) for x in r if not (x % 3)]
mf = map(process, filter(lambda x: not (x % 3), r))
print len(lc)
print len(mf)
print lc == mf

# timings

import time

print

startTime = time.clock()
lc = [process(x) for x in r if (x % 3)]
lcTime = time.clock() - startTime

print lcTime

startTime = time.clock()
mf = map(process, filter(lambda x: (x % 3), r))
mfTime = time.clock() - startTime

print mfTime

However, it would be tricky to write an automated tool which could deal with
more than just the above.

Tim Delaney




More information about the Python-list mailing list