0

I have a python-3 code that I would like to be compatible for both python-2 and python-3 keeping the code as is as much as possible. I would like to use the iteration behavior of range (to iterate over many items).

In order to get an iterator:

  • python-2 uses xrange(N)
  • python-3 uses range(N)

what is the best way to make it an iterator for python2 with minimal changes as possible?

looking at this link, it suggests a few ways for range and xrange but couldn't make it work

3
  • 1
    Detect the python version and use range = xrange if you find the user running python 2. Basically, deliberately redefine range Commented Dec 26, 2018 at 15:27
  • How large do you expect N to be? Commented Dec 26, 2018 at 15:28
  • 1
    This might be semantics, but neither xrange in python 2 nor range in python 3 return iterators, they return an xrange or range object and you can't use them with next(). Commented Dec 26, 2018 at 15:35

3 Answers 3

3

Put this near the start of the program.

import sys
import builtins

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

a = range(100)  # Keep your Python 3 code unchanged
Sign up to request clarification or add additional context in comments.

Comments

0
try:
    n_range = xrange
except NameError:
    n_range = range

We can set n_range as xrange and if it fails, set it as range.

1 Comment

I think it's much less efficient to catch exception rather than simple if
0

you can detect the version of python at runtime:

from sys import version_info
if version_info[0] < 3:
    range = xrange

this overrides the regular range behavior in python 2 so make sure your code doesn't use the python 2 range

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.