是否“向后移植"Python 3 到 Python 2 的“范围"是个坏主意? [英] Is "backporting" Python 3's `range` to Python 2 a bad idea?
问题描述
我的一个课程要求使用 Python 完成作业,作为练习,我一直使用这样的脚本确保我的程序在 Python 2 和 Python 3 中都能运行:
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
我一直在做的一件事是使用这段代码使 range
在两个版本中的工作相同:
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
这是个坏主意吗?
这样做的原因是 xrange
和 range
在 Python 2 和 Python 3 中的工作方式不同,我希望我的代码在两者中做同样的事情.我可以反过来做,但让 Python 3 像 Python 2 一样工作似乎很愚蠢,因为 Python 3 是未来".
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".
以下示例说明为什么仅使用 range
不够好:
Here's an example of why just using range
isn't good enough:
for i in range(1000000000):
do_something_with(i)
我显然没有使用列表,但在 Python 2 中,这将使用大量内存.
I'm obviously not using the list, but in Python 2, this will use an insane amount of memory.
推荐答案
您可以使用 six 包,它提供由 Python 核心开发人员之一编写的 Python 2 和 3 兼容性库.它的功能之一是重命名模块和函数的一组标准定义,包括 xrange
-> range
.6
的使用是官方Porting Python 2 Code to Python 3 中的众多推荐之一HOWTO 包含在 Python 文档集中.
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.
这篇关于是否“向后移植"Python 3 到 Python 2 的“范围"是个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!