Enabling "xrange" in Python3 for portability

I wrote a script that I wanted to include for both Python 2 and Python 3.

After importing to divisionand print_functionfrom, __future__my only problem was that mine was rangereturning an entire array in Python 2, wasting time and memory.

I added the following 3 lines at the beginning of the script as a workaround:

if sys.version_info[0] == 3:
    def xrange(i):
        return range(i)

Then I used xrangein my code.

Is there an even more elegant way to do this, and not my workaround?

+4
source share
1 answer

You can simplify it a bit:

if sys.version_info[0] == 3:
    xrange = range

I would do it the other way around:

if sys.version_info[0] == 2:
    range = xrange

- Python 2.x, , .

six. - Python 2 3.

from six.moves import range
+9

All Articles