问题
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.
回答1:
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.
回答2:
What you probably should be doing is making sure it works cleanly under 2.x, and then passing it through 2to3 and verifying that the result works cleanly in 3.x. That way you won't have to go through hoops such as redefining range
as you have already done.
来源:https://stackoverflow.com/questions/7507492/is-backporting-python-3s-range-to-python-2-a-bad-idea