Search code examples
pythonpython-3.xxrange

How can I enable xrange in Python 3 for portability?


I wrote a script which I wanted to enable for both Python 2 and Python 3.

After importing division and print_function from __future__, my only concern was that my range returns a whole 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 only used xrange in my code.

Is there some more elegant way to do it rather than my workaround?


Solution

  • 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
    

    If you ever want to drop Python 2.x support, you can just remove those two lines without going through all your code.

    However, I strongly suggest considering the six library. It is the de-facto standard for enabling Python 2 and 3 compatibility.

    from six.moves import range