One of my classes requires assignments to be completed in Python, and as an exercise, I've been making sure my programs work in both Python 2 and Python 3, using a script like this:
#!/bin/bash
# Run some PyUnit tests
python2 test.py
python3 test.py
One thing I've been doing is making range
work the same in both versions with this piece of code:
import sys
# Backport Python 3's range to Python 2 so that this program will run
# identically in both versions.
if sys.version_info < (3, 0):
range = xrange
Is this a bad idea?
EDIT:
The reason for this is that xrange
and range
work differently in Python 2 and Python 3, and I want my code to do the same thing in both. I could do it the other way around, but making Python 3 work like Python 2 seems stupid, since Python 3 is "the future".
Here's an example of why just using range
isn't good enough:
for i in range(1000000000):
do_something_with(i)
I'm obviously not using the list, but in Python 2, this will use an insane amount of memory.
Don't "mix". When the various packages and modules are available in Python 3, use the 2to3 conversion to create Python 3. You'll find some small problems. Fix your Python 2 so that your package works in Python 2 and also works after the conversion.
You can't. Any module you import in py3 codebase needs to be py3 compatible. If you can't make the upstream project do it for you, you'll have to do it yourself.
History of Python 2 vs. Python 3. Python 2 came out in 2000. The upgrade to the language was designed to make it easier for the average person to learn, but it also added many features developers needed, like list comprehension, Unicode support, garbage collection, and improved support for object-oriented programming.
So what is range? The range object is “lazy” in a sense because it doesn't generate every number that it “contains” when we create it. Instead it gives those numbers to us as we need them when looping over it. If you're looking for a description for range objects, you could call them “lazy sequences”.
You can use the six package which provides a Python 2 and 3 compatibility library and written by one of the Python core developers. Among its features is a set of standard definitions for renamed modules and functions, including xrange
-> range
. The use of six
is one of many recommendations in the official Porting Python 2 Code to Python 3 HOWTO included in the Python Documentation set.
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