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?
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
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