from __future__ import range

Hello, Below a suggestion by Paul MacGuire on the python-tutor. I found it so sensible that I asked him to propose it on python-ideas. His answer was: "Please feel free to post this on python-ideas as my proxy. I'm barely keeping up with my other pythonic duties as it is." So here it is. ==================================================== So I'll propose some usages for those who use range: 1. For Py2-Py3 range-xrange compatibility, add this code to the top of your Python scripts: try: range = xrange except NameError: pass In this way, your code under Py2 will use xrange whenever you call range, and you will adopt the future-compatible range behavior. (Hmm, maybe this would have been a good option to add to the "future" module...) 2. In all cases where you really must use the result returned from range as a list, ALWAYS write this as "list(range(n))", as in: nonnegative_numbers_up_to_but_not_including_10 = list(range(10)) even_numbers_up_to_but_not_including_20 = list(range(0,20,2)) Using the "list(range(n))" form when you actually need a list will prepare you for the change in idiom when you upgrade to Py3, and is fully Py2 compatible (even if you don't first bind xrange to range as in suggestion 1 - it simply copies the original list). It also makes it very explicit that you REALLY WANT THE RANGE AS A LIST, and not just as something for counting up to n. ==================================================== I think that from __future__ import range used together with list(range(...)) would: -1- Be a good programming practice, -2- Help & remove one of the 2to3 issues that cannot be solved automatically. Denis ------ la vita e estrany

spir wrote:
__future__ is really only for things that the compiler needs to know about. However, adding a "range = xrange" line to Lib\future_builtins.py in 2.7 probably wouldn't be a bad idea. Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia ---------------------------------------------------------------

spir wrote:
__future__ is really only for things that the compiler needs to know about. However, adding a "range = xrange" line to Lib\future_builtins.py in 2.7 probably wouldn't be a bad idea. Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia ---------------------------------------------------------------
participants (2)
-
Nick Coghlan
-
spir