Message141470
In `whatsnew/3.0.html`, there is little said about the map builtin:
map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).
This suggests that all one must do to port to Python 3 is wrap map in list, and in fact this is what the 2to3 fixers do, when in fact, map is semantically different in how it handles arguments of different lengths. Consider the following.
def to_tuple(*args):
return args
print(list(map(to_tuple, [1,2,3], [4,5,6,7])))
On Python 2, this code outputs:
[(1, 4), (2, 5), (3, 6), (None, 7)]
On Python 3, this code outputs:
[(1, 4), (2, 5), (3, 6)]
I suggest three fixes (in order of importance):
1) Document the difference in whatsnew/3.0.html.
2) Describe how one should port code of this usage to 3.0.
3) Incorporate the porting in the 2to3 fixer (if possible).
If no one objects, I'll begin on (1). Does anyone have any suggestions for a clean approach to (2)? |
|
Date |
User |
Action |
Args |
2011-07-31 15:28:14 | jaraco | set | recipients:
+ jaraco, docs@python |
2011-07-31 15:28:13 | jaraco | set | messageid: <1312126093.97.0.0321206475431.issue12666@psf.upfronthosting.co.za> |
2011-07-31 15:28:13 | jaraco | link | issue12666 messages |
2011-07-31 15:28:12 | jaraco | create | |
|