0

Lets say I have a program that needs to run in both Py 2 and Py 3. The only difference in the functionality is range vs xrange. Is it possible to do something like this?

if version == 3: pass
else: range = xrange

I know I saw something like this before, however I can't seem to find an example on the Google machine. Thanks guys.

3
  • Check sys.version_info tuple if you want to do it manually. Google for six, python-future or nine for 3rd party libraries designed to solve this problem. Commented Jan 2, 2017 at 13:35
  • 1
    if range is None: range = xrange Commented Jan 2, 2017 at 13:45
  • I like your answer the best because of the increase in compilation time. Commented Jan 2, 2017 at 13:47

2 Answers 2

1

Yes, you can do something like:

import sys
if sys.version_info.major > 2:
    xrange = range

Another approach would be to wrap the xrange statement in a try/catch block:

>>> try:
...     r = xrange(10)
... except NameError:
... # No xrange in Python3
...     r = range(10)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use sys.version_info. This is a tuple holding the version number so something like this should work:

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

If you need a more precise control for the version (minor number), you can either use major/minor that give first and second number of the version, or simply sys.version_info[:2] that is a tuple that can be used in combination with ==, >=,...

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.