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?
__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.
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.
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With