Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any __future__ import for range-xrange incompatibility?

Tags:

python

Writting for Python 2, I always use xrange, but it is renamed in Python 3. So I mostly write

if sys.version.startswith('3'):
    zrange = range
else:
    zrange = xrange

and use zrange below. Is there a more graceful solution (without depending on 3rd party package), like from __future__ import unicode_literal hopefully?

like image 312
Frozen Flame Avatar asked Jun 30 '15 11:06

Frozen Flame


People also ask

What does from __ future __ import mean?

__future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module.

How does Python __ future __ work?

Future statements tell the interpreter to compile some semantics as the semantics which will be available in the future Python version. In other words, Python uses from __future__ import feature to backport features from other higher Python versions to the current interpreter.

How do I import Xrange into Python 3?

In Python 3, there is no xrange, but the range function behaves like xrange in Python 2. If you want to write code that will run on both Python 2 and Python 3, you should use range(). range() – This returns a range object (a type of iterable).


1 Answers

No, there is no from __future__ import for this, nor do you need to use a third-party package. Simply catch the name error when xrange is not available:

try:
    zrange = xrange
except NameError:
    zrange = range

There's not really a need to test for versions.

Personally, I'd not make up a new name, just re-use range on Python 2:

try:
    # Python 2
    range = xrange
except NameError:
    # Python 3
    pass

or add xrange in Python 3 as an alias:

try:
    # Python 2
    xrange
except NameError:
    # Python 3
    xrange = range

Re-assigning range in Python 2 only is preferable, since going forward a project is far more likely to drop Python 2 support and focus on Python 3 syntax exclusively than the other way around.

Packages that need to support both Python 2 and Python 3 usually create a compat module to handle bridges like these. See the requests.compat module for example, where they do use a version test only because that limits the number of tests to just the one if.

like image 182
Martijn Pieters Avatar answered Nov 15 '22 19:11

Martijn Pieters