Issue
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.
Solution
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.
Answered By - Ned Deily
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.