[Python-ideas] from __future__ import range

spir denis.spir at free.fr
Tue Apr 21 11:58:29 CEST 2009


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:

    range = xrange
except NameError:

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
-1- Be a good programming practice,
-2- Help & remove one of the 2to3 issues that cannot be solved automatically.

la vita e estrany

More information about the Python-ideas mailing list