[Python-Dev] Release of astoptimizer 0.3
Stefan Behnel
stefan_ml at behnel.de
Tue Sep 11 21:03:58 CEST 2012
Serhiy Storchaka, 11.09.2012 20:48:
> set([1, 2, 3]) => {1, 2, 3}
> set([x for ...]) => {x for ...}
> dict([(k, v) for ...]) => {k: v for ...}
> dict((k, v) for ...) => {k: v for ...}
> ''.join([s for ...]) => ''.join(s for ...)
> a.extend([s for ...]) => a.extend(s for ...)
> (f(x) for x in a) => map(f, a)
> (x.y for x in a) => map(operator.attrgetter('y'), a)
> (x[0] for x in a) => map(operator.itemgetter(0), a)
> (2 * x for x in a) => map((2).__mul__, a)
> (x in b for x in a) => map(b.__contains__, a)
> map(lambda x: x.strip(), a) => (x.strip() for x in a)
> x in ['i', 'em', 'cite'] => x in {'i', 'em', 'cite'}
> x == 'i' or x == 'em' or x == 'cite'] => x in {'i', 'em', 'cite'}
> a = []; for ...: a.append(x) => a = [x for ...]
> a = (); for ...: a.add(x) => a = {x for ...}
> a = {}; for ...: a[k] = v => a = {k: v for ...}
> for ...: f.write(...) => __fwrite = f.write; for ...: __fwrite(...)
> x = x + 1 => x += 1
> x = x + ' ' => x += ' '
> x = x + [y] => x.append(y)
> x = x + [y, z] => x.extend([y, z])
> 'x=%s' % repr(x) => 'x=%a' % (x,)
> 'x=%s' % x + s => 'x=%s%s' % (x, s)
> x = x + ', [%s]' % y => x = '%s, [%s]' % (x, y)
> range(0, x) => range(x)
> for i in range(len(a)): x = a[i] ... => for i, x in enumerate(a): ...
> i = 0; for x in a: i += 1 ... => for i, x in enumerate(a, 1): ...
> i = 1; for x in a: ... i += 1 => for i, x in enumerate(a, 1): ...
> s = 0; for ...: if ...: s += 1 => s = sum(1 for ... if ...)
> while True: s = f.readline(); if not s: break; ... => for s in f: ...
> def f(x): ... len() ... => def f(x, __len = len): ... __len() ...
>
> Not all such transformations are always safe (and I know code in stdlib
> where they are not).
Actually, many of them are not, and some of them are even plain wrong or
may at least turn out not to be optimisations.
Stefan
More information about the Python-Dev
mailing list