py2to3 doesn't see the global picture. It just creates some equivalent code, replacing the functions that now don't create lists anymore by adding a list
wrapper, to make sure that:
- one can subscript the result
- one can iterate on the result as many times as wanted
(it also puts parentheses around print
, ... but not relevant here)
So it tries to make your code run, but the performance isn't guaranteed like at all.
In your example, the list wrapper is useless, as the dict
consumes the iterator.
So this tool is useful to make code work quickly, but should not be used without comparing to your original code and decide what to keep/what to change.
The tool could probably be improved to:
- avoid wrapping when the iterator is used in a loop
- avoid wrapping when the iterator is passed to an object which takes an iterable as input.
In your case
dict(zip(range(n), range(n)))
is perfectly fine and runs faster in python 3 than in python 2 because it avoids intermediate list creations, so leave it that way.
a python 2 equivalent of that would be slightly more complex:
dict(itertools.izip(xrange(n), xrange(n)))
My advice if you have a lot of code to translate (I've been there):
- use
python -3
switch with python 2 interpreter to expose your code and get some warnings instead of having it crash in python 3 (well, it is supposed to warn about Python 3.x incompatibilities that 2to3 cannot trivially fix, but it misses a lot of cases, well, it's better than nothing, for instance it finds the infamous has_key
calls)
- use
py2to3
and compare the results with your original code, decide manually where to apply the changes
- you can also use multi search/replace with tools like GrepWin to do what py2to3 would do, only with less risks of degrading the performance:
- search for
iteritems
, replace by items
- search for
xrange
, replace by range
- track down
dict.has_key
calls, unicode
built-in
- I may forget some...
- test and expose your code extensively with python 3. some things are invisible to the tool and the
-3
option, like when you're using binary mode to read text files and such.