与大多数语言不同,Python支持两个主要版本。自2008年Python 3发布以来,许多人已经完成了迁移,但仍有许多人没有。为了理解这两个版本,本节涵盖了Python 2和Python 3之间的重要差异。
Section 149.1: 整数除法
标准的/符号在Python 3和Python 2中对整数的操作有所不同。
在Python 3中,整数除以另一个整数时,除法操作x / y表示真除法(使用__truediv__方法),并产生一个浮点结果。而在Python 2中,相同的操作表示经典除法,结果向下取整(也称为取地板值)。
例如:
| Code | Python 2 输出 | Python 3 输出 |
|---|---|---|
| 3 / 2 | 1 | 1.5 |
| 2 / 3 | 0 | 0.6666666666666666 |
| -3 / 2 | -2 | -1.5 |
Python 2.2中弃用了向零舍入的行为,但为了向后兼容,Python 2.7中仍然保留了它,并在Python 3中被移除。
注意:要在Python 2中获得浮点结果(而不是向下取整),我们可以在操作数中指定一个小数点。例如,2 / 3在Python 2中返回0,可以写成2 / 3.0、2.0 / 3或2.0 / 3.0以获得0.6666666666666666。
| Code | Python 2 输出 | Python 3 输出 |
|---|---|---|
| 3.0 / 2.0 | 1.5 | 1.5 |
| 2 / 3.0 | 0.6666666666666666 | 0.6666666666666666 |
| -3.0 / 2 | -1.5 | -1.5 |
还有地板除运算符(//),它在两个版本中的行为相同:它将结果向下舍入到最近的整数。(尽管使用浮点数时会返回一个浮点数)在两个版本中,//运算符都映射到__floordiv__。
| Code | Python 2 输出 | Python 3 输出 |
|---|---|---|
| 3 // 2 | 1 | 1 |
| 2 // 3 | 0 | 0 |
| -3 // 2 | -2 | -2 |
| 3.0 // 2.0 | 1.0 | 1.0 |
| 2.0 // 3 | 0.0 | 0.0 |
| -3 // 2.0 | -2.0 | -2.0 |
可以使用operator模块中的原生函数显式强制执行真除法或浮点数除法:
from operator import truediv, floordiv
assert truediv(10, 8) == 1.25 # equivalent to `/` in Python 3
assert floordiv(10, 8) == 1 # equivalent to `//`
虽然清晰明确,但使用运算符函数进行每次除法可能会很繁琐。通常更倾向于改变/运算符的行为。一种常见的做法是通过在每个模块的开头添加from __future__ import division来消除典型除法行为:
# needs to be the first statement in a module
from __future__ import division
| Code | Python 2 输出 | Python 3 输出 |
|---|---|---|
| 3 / 2 | 1.5 | 1.5 |
| 2 / 3 | 0.6666666666666666 | 0.6666666666666666 |
| -3 / 2 | -1.5 | -1.5 |
from __future__ import division保证/运算符表示真除法,并且仅在包含__future__导入的模块内有效,因此没有理由不在所有新模块中启用它。
注意:一些其他编程语言使用向零舍入(截断),而不是像Python那样向下舍入到负无穷大(即在这些语言中-3 / 2 == -1)。这种行为可能会在移植或比较代码时造成混淆。
关于浮点运算符的注意事项:作为from __future__ import division的替代方法,可以使用普通的除法符号/,并确保至少有一个操作数是浮点数:3 / 2.0 == 1.5。然而,这可能被认为是一种不好的实践。很容易写出average = sum(items) / len(items)并忘记将其中一个参数转换为浮点数。此外,这种问题可能在测试期间经常被忽视,例如,如果你在测试中使用的是包含floats的数组,但在生产环境中收到的是ints数组。此外,如果相同的代码在Python 3中使用,期望3 / 2 == 1为True的程序将无法正确工作。
有关更改Python 3中的除法运算符以及为什么应该避免旧式除法的更详细理由,请参阅PEP 238。
有关除法的更多信息,请参阅简单数学主题。
Section 149.2: 解包可迭代对象
Python 3.x版本 ≥ 3.0
在Python 3中,你可以解包一个可迭代对象,而无需知道其中的确切项目数量,甚至可以让一个变量保存可迭代对象的末尾。为此,你需要提供一个可以收集值列表的变量。这可以通过在名称前放置星号来完成。例如,解包一个列表:
first, second, *tail, last = [1, 2, 3, 4, 5]
print(first)
# Out: 1
print(second)
# Out: 2
print(tail)
# Out: [3, 4]
print(last)
# Out: 5
注意:使用*变量语法时,变量将始终是一个列表,即使原始类型不是列表也是如此。它可能根据原始列表中的元素数量包含零个或多个元素。
first, second, *tail, last = [1, 2, 3, 4]
print(tail)
# Out: [3]
first, second, *tail, last = [1, 2, 3]
print(tail)
# Out: []
print(last)
# Out: 3
类似地,解包一个str:
begin, *tail = "Hello"
print(begin)
# Out: 'H'
print(tail)
# Out: ['e', 'l', 'l', 'o']
解包日期的示例;在此示例中,_用作临时变量(我们只对年份值感兴趣):
person = ('John', 'Doe', (10, 16, 2016))
*_, (*_, year_of_birth) = person
print(year_of_birth)
# Out: 2016
值得一提的是,由于*会吸收可变数量的项目,因此你不能在同一个可迭代对象的赋值中使用两个*,因为它不知道有多少元素进入第一次解包,以及有多少进入第二次:
*head, *tail = [1, 2]
# Out: SyntaxError: two starred expressions in assignment
Python 3.x Version ≥ 3.5
到目前为止,我们已经讨论了在赋值中的解包。在Python 3.5中,*和**被扩展了。现在可以在一个表达式中进行多个解包操作:
{*range(4), 4, *(5, 6, 7)}
# Out: {0, 1, 2, 3, 4, 5, 6, 7}
Python 2.x Version ≥ 2.0
也可以将可迭代对象解包为函数参数:
iterable = [1, 2, 3, 4, 5]
print(iterable)
# Out: [1, 2, 3, 4, 5]
print(*iterable)
# Out: 1 2 3 4 5
Python 3.x Version ≥ 3.5
解包字典使用两个相邻的星号**(PEP 448):
tail = {'y': 2, 'z': 3}
{'x': 1, **tail}
# Out: {'x': 1, 'y': 2, 'z': 3}
这允许覆盖旧值和合并字典。
dict1 = {'x': 1, 'y': 1}
dict2 = {'y': 2, 'z': 3}
{**dict1, **dict2}
# Out: {'x': 1, 'y': 2, 'z': 3}
Python 3.x Version ≥ 3.0
Python 3移除了函数中的元组解包。因此,以下代码在Python 3中不起作用:
# Works in Python 2, but syntax error in Python 3:
map(lambda (x, y): x + y, zip(range(5), range(5)))
# Same is true for non-lambdas:
def example((x, y)):
pass
# Works in both Python 2 and Python 3:
map(lambda x: x[0] + x[1], zip(range(5), range(5)))
# And non-lambdas, too:
def working_example(x_y):
x, y = x_y
pass
有关详细理由,请参阅PEP 3113。
Section 149.3: 字符串:字节与Unicode
Python 2.x Version ≤ 2.7
在Python 2中,存在两种字符串变体:由字节组成的类型(str)和由文本组成的类型(unicode)。
在Python 2中,str类型的对象始终是一个字节序列,但通常用于表示文本和二进制数据。
字符串字面量被解释为字节字符串。
s = 'Cafe' # type(s) == str
有两个例外:你可以通过在字面量前加上u来显式定义一个Unicode(文本)字面量:
s = u'Caf.' # type(s) == unicode
b = 'Lorem ipsum' # type(b) == str
或者,你可以指定整个模块的字符串字面量应创建Unicode(文本)字面量:
from __future__ import unicode_literals
s = 'Caf.' # type(s) == unicode
b = 'Lorem ipsum' # type(b) == unicode
为了检查变量是否为字符串(无论是Unicode还是字节字符串),可以使用:
isinstance(s, basestring)
Python 3.x Version ≥ 3.0
在Python 3中,str类型是一个Unicode文本类型。
s = 'Cafe' # type(s) == str
s = 'Caf.' # type(s) == str (note the accented trailing e)
此外,Python 3添加了一个bytes对象,适用于二进制“块”或写入编码无关的文件。要创建一个bytes对象,可以在字符串字面量前加上b,或者调用字符串的encode方法:
# Or, if you really need a byte string:
s = b'Cafe' # type(s) == bytes
s = 'Caf.'.encode() # type(s) == bytes
要测试一个值是否为字符串,可以使用:
isinstance(s, str)
Python 3.x Version ≥ 3.3
也可以在字符串字面量前加上u前缀,以方便Python 2和Python 3代码库之间的兼容性。由于在Python 3中,所有字符串默认都是Unicode,因此在字符串字面量前加上u没有效果:
u'Cafe' == 'Cafe'
但是,Python 2的原始Unicode字符串前缀ur不被支持:
>>> ur'Caf.'
File "<stdin>", line 1
ur'Caf.'
^
SyntaxError: invalid syntax
注意,你必须将Python 3中的text (str)对象encode转换为其字节表示。此方法的默认编码是UTF-8。
你可以使用decode询问bytes对象它所代表的Unicode文本:
>>> b.decode()
'Caf.'
Python 2.x Version ≥ 2.6
虽然bytes类型在Python 2和Python 3中都存在,但unicode类型仅存在于Python 2中。要在Python 2中使用Python 3的隐式Unicode字符串,可以在代码文件的顶部添加以下内容:
from __future__ import unicode_literals
print(repr("hi"))
\# u'hi'
Python 3.x Version ≥ 3.0
另一个重要区别是,在Python 3中,对字节进行索引的结果是一个int输出,如下所示:
b"abc"[0] == 97
而以大小为1进行切片的结果是一个长度为1的字节对象:
b"abc"[0:1] == b"a"
此外,从Python 3.2开始,range也支持切片、索引和计数:
Python复制
print(range(1, 10)[3:7])
# 输出:range(3, 7)
print(range(1, 10).count(5))
# 输出:1
print(range(1, 10).index(7))
# 输出:6
使用特殊序列类型而不是列表的优点是,解释器不需要分配内存来创建列表并填充它:
Python 2.x版本 ≥ 2.3
# range(10000000000000000)
# 输出:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# MemoryError
print(xrange(100000000000000000))
# 输出:xrange(100000000000000000)
由于后一种行为通常是期望的,因此在Python 3中移除了前一种行为。如果你仍然希望在Python 3中获得一个列表,你可以简单地使用list()构造函数对范围对象进行操作:
Python 3.x版本 ≥ 3.0
Python复制
print(list(range(1, 10)))
# 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
兼容性
为了在Python 2.x和Python 3.x版本之间保持兼容性,你可以使用外部包future中的builtins模块来实现向前兼容和向后兼容:
Python 2.x版本 ≥ 2.0
Python复制
# 向前兼容
from builtins import range
for i in range(10**8):
pass
Python 3.x版本 ≥ 3.0
Python复制
# 向后兼容
from past.builtins import xrange
for i in xrange(10**8):
pass
future库中的range支持在所有Python版本中进行切片、索引和计数,就像Python 3.2+中的内置方法一样。
Section 149.4: print语句与print函数
在Python 2中,print是一个语句:
Python 2.x Version ≤ 2.7
print "Hello World"
print # print a newline
print "No newline", # add trailing comma to remove newline
print >>sys.stderr, "Error" # print to stderr
print("hello") # print "hello", since ("hello") == "hello"
print() # print an empty tuple "()"
print 1, 2, 3 # print space-separated arguments: "1 2 3"
print(1, 2, 3) # print tuple "(1, 2, 3)"
在Python 3中,print()是一个函数,具有用于常见用途的关键字参数:
Python 3.x Version ≥ 3.0
print "Hello World" # SyntaxError
print("Hello World")
print() # print a newline (must use parentheses)
print("No newline", end="") # end specifies what to append (defaults to newline)
print("Error", file=sys.stderr) # file specifies the output buffer
print("Comma", "separated", "output", sep=",") # sep specifies the separator
print("A", "B", "C", sep="") # null string for sep: prints as ABC
print("Flush this", flush=True) # flush the output buffer, added in Python 3.3
print(1, 2, 3) # print space-separated arguments: "1 2 3"
print((1, 2, 3)) # print tuple "(1, 2, 3)"
print函数具有以下参数:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
sep是分隔你传递给print的对象的内容。例如:
print('foo', 'bar', sep='~') # out: foo~bar
print('foo', 'bar', sep='.') # out: foo.bar
end是print语句末尾跟随的内容。例如:
print('foo', 'bar', end='!') # out: foo bar!
再次打印时,如果print语句以非换行符结尾,将打印在同一行:
print('foo', end='~')
print('bar')
\# out: foo~bar
注意:为了与未来版本兼容,print函数在Python 2.6及以后版本中也可用;但是,除非使用
from __future__ import print_function
禁用了print语句的解析,否则无法使用它。
有关理由,请参阅PEP 3105。
Section 149.5: range和xrange函数之间的差异
在Python 2中,range函数返回一个列表,而xrange创建一个特殊的xrange对象,这是一个不可变序列,与其他内置序列类型不同,它不支持切片,也没有index或count方法:
Python 2.x Version ≥ 2.3
print(range(1, 10))
# Out: [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(isinstance(range(1, 10), list))
# Out: True
print(xrange(1, 10))
# Out: xrange(1, 10)
print(isinstance(xrange(1, 10), xrange))
# Out: True
在Python 3中,xrange被扩展为range序列,因此现在创建一个range对象。没有xrange类型:
Python 3.x Version ≥ 3.0
print(range(1, 10))
# Out: range(1, 10)
print(isinstance(range(1, 10), range))
# Out: True
# print(xrange(1, 10))
# The output will be:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# NameError: name 'xrange' is not defined
此外,从Python 3.2开始,range也支持切片、索引和计数:
print(range(1, 10)[3:7])
# Out: range(3, 7)
print(range(1, 10).count(5))
# Out: 1
print(range(1, 10).index(7))
# Out: 6
使用特殊序列类型而不是列表的优点是,解释器不需要分配内存来创建列表并填充它:
Python 2.x Version ≥ 2.3
# range(10000000000000000)
# The output would be:
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# MemoryError
print(xrange(100000000000000000))
# Out: xrange(100000000000000000)
由于后一种行为通常是期望的,因此在Python 3中移除了前一种行为。如果你仍然希望在Python 3中获得一个列表,你可以简单地使用list()构造函数对range对象进行操作:
Python 3.x Version ≥ 3.0
print(list(range(1, 10)))
# Out: [1, 2, 3, 4, 5, 6, 7, 8, 9]
兼容性
为了在Python 2.x和Python 3.x版本之间保持兼容性,你可以使用外部包future中的builtins模块来实现向前兼容和向后兼容:
Python 2.x Version ≥ 2.0
#forward-compatible
from builtins import range
for i in range(10**8):
pass
Python 3.x Version ≥ 3.0
#backward-compatible
from past.builtins import xrange
for i in xrange(10**8):
pass
future库中的range在所有Python版本中都支持切片、索引和计数,就像Python 3.2+中的内置方法一样。
Section 149.6: 抛出和处理异常
这是Python 2的语法,注意raise和except行上的逗号:
Python 2.x Version ≥ 2.3
try:
raise IOError, "input/output error"
except IOError, exc:
print exc
在Python 3中,逗号语法被丢弃并替换为括号和as关键字:
try:
raise IOError("input/output error")
except IOError as exc:
print(exc)
为了向后兼容,Python 3的语法在Python 2.6及以后版本中也可用,因此应该用于所有不需要与以前版本兼容的新代码。
Python 3.x Version ≥ 3.0
Python 3还添加了异常链,你可以在这里标记其他异常是导致此异常的原因。例如:
try:
file = open('database.db')
except FileNotFoundError as e:
raise DatabaseError('Cannot open {}') from e
在except语句中引发的异常类型为DatabaseError,但原始异常被标记为该异常的__cause__属性。当显示回溯时,原始异常也会显示在回溯中:
Traceback (most recent call last):
File "", line 2, in
FileNotFoundError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "", line 4, in
DatabaseError('Cannot open database.db')
如果你在except块中抛出异常,但没有明确链式:
try:
file = open('database.db')
except FileNotFoundError as e:
raise DatabaseError('Cannot open {}')
回溯是:
Traceback (most recent call last):
File "", line 2, in
FileNotFoundError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "", line 4, in
DatabaseError('Cannot open database.db')
Python 2.x Version ≥ 2.0
在Python 2.x中,两者都不受支持;如果在except块中引发另一个异常,原始异常及其回溯将丢失。以下代码可用于兼容性:
import sys
import traceback
try:
funcWithError()
except:
sys_vers = getattr(sys, 'version_info', (0,))
if sys_vers < (3, 0):
traceback.print_exc()
raise Exception("new exception")
Python 3.x Version ≥ 3.3
要“忘记”之前抛出的异常,使用raise from None:
try:
file = open('database.db')
except FileNotFoundError as e:
raise DatabaseError('Cannot open {}') from None
现在回溯将仅仅是:
Traceback (most recent call last):
File "", line 4, in
DatabaseError('Cannot open database.db')
或者,为了使其与Python 2和3都兼容,你可以使用six包如下:
import six
try:
file = open('database.db')
except FileNotFoundError as e:
six.raise_from(DatabaseError('Cannot open {}'), None)
Section 149.7: 列表推导式中的变量泄露
Python 2.x Version ≥ 2.3
x = 'hello world!'
vowels = [x for x in 'AEIOU']
print (vowels)
# Out: ['A', 'E', 'I', 'O', 'U']
print(x)
# Out: 'U'
Python 3.x Version ≥ 3.0
x = 'hello world!'
vowels = [x for x in 'AEIOU']
print (vowels)
# Out: ['A', 'E', 'I', 'O', 'U']
print(x)
# Out: 'hello world!'
从示例中可以看出,在Python 2中,x的值被泄露了:它掩盖了hello world!,并打印出U,因为这是循环结束时x的最后一个值。
然而,在Python 3中,x打印出最初定义的hello world!,因为列表推导式中的局部变量不会掩盖周围作用域中的变量。
此外,在Python 2中,生成器表达式(自Python 2.5以来可用)、字典或集合推导式(从Python 3回退到Python 2.7)不会泄露变量。
注意,在Python 2和Python 3中,使用for循环时,变量会泄露到周围作用域:
x = 'hello world!'
vowels = []
for x in 'AEIOU':
vowels.append(x)
print(x)
# Out: 'U'
Section 149.8: True, False 和 None
在Python 2中,True、False和None是内置常量。这意味着可以重新分配它们。
Python 2.x Version ≥ 2.0
True, False = False, True
True # False
False # True
从Python 2.4开始,你不能对None进行赋值。
Python 2.x Version ≥ 2.4
None = None # SyntaxError: cannot assign to None
在Python 3中,True、False和None现在是关键字。
Python 3.x Version ≥ 3.0
True, False = False, True # SyntaxError: can't assign to keyword
None = None # SyntaxError: can't assign to keyword
Section 149.9: 用户输入
在Python 2中,使用raw_input函数接受用户输入,
Python 2.x Version ≥ 2.3
user_input = raw_input()
而在Python 3中,使用input函数接受用户输入。
Python 3.x Version ≥ 3.0
user_input = input()
在Python 2中,input函数将接受输入并进行解释。虽然这可能很有用,但它存在几个安全问题,并且在Python 3中被移除。为了访问相同的功能,可以使用eval(input())。
为了使脚本在两个版本之间具有可移植性,可以在Python脚本的顶部放置以下代码:
try:
input = raw_input
except NameError:
pass
Section 149.10: 不同类型之间的比较
Python 2.x Version ≥ 2.3
在Python 2中,可以比较不同类型的对象。结果是任意的,但是一致的。它们被排序,使得None小于任何其他东西,数值类型小于非数值类型,其他一切都是按类型字典顺序排序的。因此,一个int小于一个str,而一个tuple大于一个list:
[1, 2] > 'foo'
# Out: False
(1, 2) > 'foo'
# Out: True
[1, 2] > (1, 2)
# Out: False
100 < [1, 'x'] < 'xyz' < (1, 'x')
# Out: True
这最初是为了能够对混合类型的列表进行排序,并且对象会按类型分组:
l = [7, 'x', (1, 2), [5, 6], 5, 8.0, 'y', 1.2, [7, 8], 'z']
sorted(l)
# Out: [1.2, 5, 7, 8.0, [5, 6], [7, 8], 'x', 'y', 'z', (1, 2)]
Python 3.x Version ≥ 3.0
在Python 3中,比较不同类型(非数值类型)时会引发异常:
1 < 1.5
# Out: True
[1, 2] > 'foo'
# TypeError: unorderable types: list() > str()
(1, 2) > 'foo'
# TypeError: unorderable types: tuple() > str()
[1, 2] > (1, 2)
# TypeError: unorderable types: list() > tuple()
为了在Python 3中对混合列表按类型排序并实现版本之间的兼容性,你需要为sorted函数提供一个键:
>>> list = [1, 'hello', [3, 4], {'python': 2}, 'stackoverflow', 8, {'python': 3}, [5, 6]]
>>> sorted(list, key=str)
# Out: [1, 8, [3, 4], [5, 6], 'hello', 'stackoverflow', {'python': 2}, {'python': 3}]
使用str作为键函数会暂时将每个项目转换为字符串,仅用于比较目的。然后它会看到以[, ', {或0-9开头的字符串表示,并且能够对它们(以及所有后续字符)进行排序。
Section 149.11: 迭代器上的.next()方法重命名
在Python 2中,可以通过在迭代器本身上使用next方法来遍历迭代器:
Python 2.x Version ≥ 2.3
g = (i for i in range(0, 3))
g.next() # Yields 0
g.next() # Yields 1
g.next() # Yields 2
在Python 3中,.next方法已被重命名为.__next__,以承认其“魔法”角色,因此调用.next将引发AttributeError。在Python 2和Python 3中正确访问此功能的方式是将迭代器作为参数调用next函数。
Python 3.x Version ≥ 3.0
g = (i for i in range(0, 3))
next(g) # Yields 0
next(g) # Yields 1
next(g) # Yields 2
此代码在2.6到当前版本之间具有可移植性。
Section 149.12: filter()、map()和zip()返回迭代器而不是序列
Python 2.x Version ≤ 2.7
在Python 2中,filter、map和zip内置函数返回一个序列。map和zip始终返回一个list,而filter的返回类型取决于给定参数的类型:
>>> s = filter(lambda x: x.isalpha(), 'a1b2c3')
>>> s
'abc'
>>> s = map(lambda x: x * x, [0, 1, 2])
>>> s
[0, 1, 4]
>>> s = zip([0, 1, 2], [3, 4, 5])
>>> s
[(0, 3), (1, 4), (2, 5)]
Python 3.x Version ≥ 3.0
在Python 3中,filter、map和zip返回迭代器而不是序列:
>>> it = filter(lambda x: x.isalpha(), 'a1b2c3')
>>> it
<filter object at 0x00000098A55C2518>
>>> ''.join(it)
'abc'
>>> it = map(lambda x: x * x, [0, 1, 2])
>>> it
<map object at 0x000000E0763C2D30>
>>> list(it)
[0, 1, 4]
>>> it = zip([0, 1, 2], [3, 4, 5])
>>> it
<zip object at 0x000000E0763C52C8>
>>> list(it)
[(0, 3), (1, 4), (2, 5)]
由于Python 2中itertools.izip等同于Python 3中的zip,因此在Python 3中移除了izip。
Section 149.13: 重命名的模块
标准库中的一些模块已被重命名:
| 旧名称 | 新名称 |
|---|---|
_winreg |
winreg |
ConfigParser |
configparser |
copy_reg |
copyreg |
Queue |
queue |
SocketServer |
socketserver |
_markupbase |
markupbase |
repr |
reprlib |
test.test_support |
test.support |
Tkinter |
tkinter |
tkFileDialog |
tkinter.filedialog |
urllib / urllib2 |
urllib, urllib.parse, urllib.error, urllib.response, urllib.request, urllib.robotparser |
一些模块甚至从文件转换为库。以tkinter和urllib为例。
兼容性
当在Python 2.x和3.x版本之间保持兼容性时,你可以使用外部包future来启用在Python 2.x版本中使用Python 3.x名称导入顶级标准库包。
Section 149.14: 移除<>和``运算符,分别等同于!=和repr()`
在Python 2中,<>是!=的同义词;同样地,foo是repr(foo)的同义词。
Python 2.x Version ≤ 2.7
>>> 1 <> 2
True
>>> 1 <> 1
False
>>> foo = 'hello world'
>>> repr(foo)
"'hello world'"
>>> `foo`
"'hello world'"
Python 3.x Version ≥ 3.0
>>> 1 <> 2
File "<stdin>", line 1
1 <> 2
^
SyntaxError: invalid syntax
>>> `foo`
File "<stdin>", line 1
`foo`
^
SyntaxError: invalid syntax
Section 149.15: long与int
在Python 2中,任何大于C ssize_t的整数都会被转换为long数据类型,这在字面量中用L后缀表示。例如,在32位构建的Python中:
Python 2.x Version ≤ 2.7
>>> 2**31
2147483648L
>>> type(2**31)
<type 'long'>
>>> 2**30
1073741824
>>> type(2**30)
<type 'int'>
>>> 2**31 - 1 # 2**31 is long and long - int is long
2147483647L
然而,在Python 3中,移除了long数据类型;无论整数有多大,它都将是int。
Python 3.x Version ≥ 3.0
2**1024
# Output:
179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
print(-(2**1024))
# Output:
-179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
type(2**1024)
# Output: <class 'int'>
Section 149.16: 在Python 3中,所有类都是“新式类”
在Python 3.x中,所有类都是新式类;在定义一个新类时,Python会隐式地使其继承自object。因此,在类定义中指定object是完全可选的:
Python 3.x Version ≥ 3.0
class X: pass
class Y(object): pass
这两个类现在都包含object在其方法解析顺序(mro)中:
Python 3.x Version ≥ 3.0
>>> X.__mro__
(__main__.X, object)
>>> Y.__mro__
(__main__.Y, object)
在Python 2.x中,默认情况下,类是旧式类;它们不会隐式地继承自object。这导致类的语义取决于我们是否显式地将object作为基类添加:
Python 2.x Version ≥ 2.3
class X: pass
class Y(object): pass
在这种情况下,如果我们尝试打印Y的__mro__,将出现与Python 3.x情况类似的输出:
Python 2.x Version ≥ 2.3
>>> Y.__mro__
(<class '__main__.Y'>, <type 'object'>)
这是因为我们在定义Y时显式地使其继承自object:class Y(object): pass。对于没有继承自object的类X,__mro__属性不存在,尝试访问它将导致AttributeError。
为了确保与Python的两个版本兼容,类可以定义为以object为基类:
class mycls(object):
"""I am fully compatible with Python 2/3"""
或者,如果在全局作用域中将__metaclass__变量设置为type,则在给定模块中随后定义的所有类都将隐式地成为新式类,而无需显式地继承自object:
__metaclass__ = type
class mycls:
"""I am also fully compatible with Python 2/3"""
Section 149.17: reduce不再是内置函数
在Python 2中,reduce可以作为内置函数使用,也可以从functools包中使用(从2.6版本开始),而在Python 3中,reduce仅从functools中可用。然而,reduce在Python 2和Python 3中的语法是相同的,即reduce(function_to_reduce, list_to_reduce)。
例如,让我们考虑通过将相邻数字相除将列表简化为一个值。这里我们使用operator库中的truediv函数。
在Python 2中,这很简单:
Python 2.x Version ≥ 2.3
>>> my_list = [1, 2, 3, 4, 5]
>>> import operator
>>> reduce(operator.truediv, my_list)
0.008333333333333333
在Python 3中,示例变得稍微复杂一些:
Python 3.x Version ≥ 3.0
>>> my_list = [1, 2, 3, 4, 5]
>>> import operator, functools
>>> functools.reduce(operator.truediv, my_list)
0.008333333333333333
我们也可以使用from functools import reduce来避免使用命名空间名称调用reduce。
Section 149.18: 绝对/相对导入
在Python 3中,PEP 404改变了Python 2中导入的工作方式。不再允许在包中使用隐式相对导入,from ... import *导入仅允许在模块级别代码中使用。
为了在Python 2中实现Python 3的行为:
- 可以通过
from __future__ import absolute_import启用absolute_import功能 - 鼓励使用显式相对导入,而不是隐式相对导入
为了澄清,在Python 2中,一个模块可以通过以下方式导入位于同一目录中的另一个模块的内容:
import foo
注意,仅从导入语句中无法确定foo的位置。因此,这种类型的隐式相对导入被不推荐使用,而推荐使用显式相对导入,如下所示:
from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path
点.允许明确声明模块在目录树中的位置。
关于相对导入的更多信息
考虑一个名为shapes的用户定义包。目录结构如下:
shapes
├── __init__.py
|
├── circle.py
|
├── square.py
|
└── triangle.py
circle.py、square.py和triangle.py都作为模块导入了util.py。它们将如何引用同一级别的模块?
from . import util # use util.PI, util.sq(x), etc
或者
from .util import * #use PI, sq(x), etc to call functions
.用于同一级别的相对导入。
现在,考虑shapes模块的另一种布局:
shapes
├── __init__.py
|
├── circle
│ ├── __init__.py
│ └── circle.py
|
├── square
│ ├── __init__.py
│ └── square.py
|
├── triangle
│ ├── __init__.py
│ ├── triangle.py
|
└── util.py
现在,这三个类将如何引用util.py?
from .. import util # use util.PI, util.sq(x), etc
或者
from ..util import * # use PI, sq(x), etc to call functions
..用于父级别的相对导入。根据父级和子级之间的级别数量,添加相应数量的.。
Section 149.19: map()
map()是一个内置函数,用于对可迭代对象的元素应用函数。在Python 2中,map返回一个列表。在Python 3中,map返回一个map对象,这是一个生成器。
# Python 2.X
>>> map(str, [1, 2, 3, 4, 5])
['1', '2', '3', '4', '5']
>>> type(_)
>>> <class 'list'>
# Python 3.X
>>> map(str, [1, 2, 3, 4, 5])
<map object at 0x*>
>>> type(_)
<class 'map'>
# 我们需要再次应用map,因为我们“消耗”了之前的map....
>>> map(str, [1, 2, 3, 4, 5])
>>> list(_)
['1', '2', '3', '4', '5']
在Python 2中,你可以传递None作为map的函数参数,以用作恒等函数。在Python 3中,这不再有效。
Python 2.x Version ≥ 2.3
>>> map(None, [0, 1, 2, 3, 0, 4])
[0, 1, 2, 3, 0, 4]
Python 3.x Version ≥ 3.0
>>> list(map(None, [0, 1, 2, 3, 0, 5]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
此外,在Python 2中,传递多个可迭代对象作为参数时,map会用None填充较短的可迭代对象(类似于itertools.izip_longest)。在Python 3中,迭代会在最短的可迭代对象结束时停止。
在Python 2中:
Python 2.x Version ≥ 2.3
>>> map(None, [1, 2, 3], [1, 2], [1, 2, 3, 4, 5])
[(1, 1, 1), (2, 2, 2), (3, None, 3), (None, None, 4), (None, None, 5)]
在Python 3中:
Python 3.x Version ≥ 3.0
>>> list(map(lambda x, y, z: (x, y, z), [1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))
[(1, 1, 1), (2, 2, 2)]
# 为了在Python 2中获得相同的填充效果,请使用itertools中的zip_longest
>>> import itertools
>>> list(itertools.zip_longest([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]))
[(1, 1, 1), (2, 2, 2), (3, None, 3), (None, None, 4), (None, None, 5)]
注意:考虑使用列表推导式代替map,因为它们在Python 2和Python 3中都是兼容的。替换map(str, [1, 2, 3, 4, 5]):
>>> [str(i) for i in [1, 2, 3, 4, 5]]
['1', '2', '3', '4', '5']
Section 149.20: round()函数的四舍五入规则和返回类型
round()四舍五入规则
在Python 2中,使用round()对一个与两个整数等距离的数字进行四舍五入时,会返回离0最远的那个整数。例如:
Python 2.x Version ≤ 2.7
round(1.5) # Out: 2.0
round(0.5) # Out: 1.0
round(-0.5) # Out: -1.0
round(-1.5) # Out: -2.0
然而,在Python 3中,round()会返回偶数整数(也称为银行家舍入)。例如:
Python 3.x Version ≥ 3.0
round(1.5) # Out: 2
round(0.5) # Out: 0
round(-0.5) # Out: 0
round(-1.5) # Out: -2
round()函数遵循半舍入到偶数的四舍五入策略,现在round(2.5)返回2而不是3.0。
根据维基百科的参考,这还被称为无偏四舍五入、收敛四舍五入、统计学家四舍五入、荷兰四舍五入、高斯四舍五入或奇偶四舍五入。
半舍入到偶数的四舍五入是IEEE 754标准的一部分,也是微软.NET中的默认四舍五入模式。
这种四舍五入策略倾向于减少总四舍五入误差。由于平均而言,向上舍入的数字量与向下舍入的数字量相同,因此四舍五入误差相互抵消。其他四舍五入方法则倾向于存在向上或向下的偏差。
round()返回类型
在Python 2.7中,round()函数返回一个float类型。
Python 2.x Version ≤ 2.7
round(4.8)
# 5.0
从Python 3.0开始,如果省略第二个参数(小数位数),则返回一个int。
Python 3.x Version ≥ 3.0
round(4.8)
# 5
Section 149.21: 文件 I/O
在Python 3中,file不再是内置名称(open仍然有效)。
文件I/O的内部细节已被移至标准库中的io模块,这也是StringIO的新家:
import io
assert io.open is open # the builtin is an alias
buffer = io.StringIO()
buffer.write('hello, ') # returns number of characters written
buffer.write('world!\n')
buffer.getvalue() # 'hello, world!\n'
文件模式(文本与二进制)现在决定了读取文件时产生的数据类型(以及写入时所需的类型):
with open('data.txt') as f:
first_line = next(f)
assert type(first_line) is str
with open('data.bin', 'rb') as f:
first_kb = f.read(1024)
assert type(first_kb) is bytes
文本文件的编码默认为locale.getpreferredencoding(False)返回的值。要显式指定编码,请使用encoding关键字参数:
with open('old_japanese_poetry.txt', 'shift_jis') as text:
haiku = text.read()
Section 149.22: Python 3中移除cmp函数
在Python 3中,cmp内置函数以及__cmp__特殊方法被移除。
根据文档:
cmp()函数应视为已不存在,__cmp__()特殊方法不再受支持。使用
__lt__()进行排序,__eq__()与__hash__()一起使用,以及根据需要使用其他富比较方法。(如果你真的需要cmp()的功能,可以使用表达式(a > b) - (a < b)作为cmp(a, b)的等效物。)
此外,所有接受cmp参数的内置函数现在只接受key关键字参数。
在functools模块中,还有一个有用的函数cmp_to_key(func),它允许你将cmp风格的函数转换为key风格的函数:
将旧风格的比较函数转换为键函数。用于接受键函数的工具(例如
sorted()、min()、max()、heapq.nlargest()、heapq.nsmallest()、itertools.groupby())。此函数主要用于正在从Python 2转换为Python 3的程序。
Section 149.23: 八进制常量
在Python 2中,可以这样定义八进制字面量:
>>> 0755 # only Python 2
为了确保跨版本兼容性,请使用:
0o755 # both Python 2 and Python 3
Section 149.24: 写入文件对象时的返回值
在Python 2中,直接写入文件句柄会返回None:
Python 2.x Version ≥ 2.3
hi = sys.stdout.write('hello world\\n')
# Out: hello world
type(hi)
# Out: <type 'NoneType'>
在Python 3中,写入句柄会返回写入的字符数(写入文本时)或写入的字节数(写入字节时):
Python 3.x Version ≥ 3.0
import sys
char_count = sys.stdout.write('hello world ?\\n')
# Out: hello world ?
char_count
# Out: 14
byte_count = sys.stdout.buffer.write(b'hello world \\xf0\\x9f\\x90\\x8d\\n')
# Out: hello world ?
byte_count
# Out: 17
Section 149.25: Python 3中exec语句是函数
在Python 2中,exec是一个语句,具有特殊的语法:exec code [in globals[, locals]]。在Python 3中,exec现在是一个函数:exec(code, [, globals[, locals]]),Python 2中的语法将引发SyntaxError。
正如print从语句变为函数一样,也添加了一个__future__导入。然而,没有from __future__ import exec_function,因为不需要:Python 2中的exec语句也可以使用与Python 3中exec函数调用完全相同的语法。因此,你可以将语句
Python 2.x Version ≥ 2.3
exec 'code'
exec 'code' in global_vars
exec 'code' in global_vars, local_vars
更改为形式
Python 3.x Version ≥ 3.0
exec('code')
exec('code', global_vars)
exec('code', global_vars, local_vars)
后者的形式保证在Python 2和Python 3中完全相同地工作。
Section 149.26: 编码/解码为十六进制不再可用
Python 2.x Version ≤ 2.7
"1deadbeef3".decode('hex')
# Out: '\x1d\xea\xdb\xee\xf3'
'\x1d\xea\xdb\xee\xf3'.encode('hex')
# Out: 1deadbeef3
Python 3.x Version ≥ 3.0
"1deadbeef3".decode('hex')
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: 'str' object has no attribute 'decode'
b"1deadbeef3".decode('hex')
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
'\x1d\xea\xdb\xee\xf3'.encode('hex')
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
b'\x1d\xea\xdb\xee\xf3'.encode('hex')
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# AttributeError: 'bytes' object has no attribute 'encode'
然而,正如错误消息所建议的那样,你可以使用codecs模块来实现相同的结果:
import codecs
codecs.decode('1deadbeef4', 'hex')
# Out: b'\x1d\xea\xdb\xee\xf4'
codecs.encode(b'\x1d\xea\xdb\xee\xf4', 'hex')
# Out: b'1deadbeef4'
注意,codecs.encode返回一个字节对象。要获得字符串对象,只需解码为ASCII:
codecs.encode(b'\x1d\xea\xdb\xee\xff', 'hex').decode('ascii')
# Out: '1deadbeeff'
Section 149.27: 字典方法更改
在Python 3中,许多字典方法的行为与Python 2不同,许多方法也被移除了:has_key、iter*和view*。作为d.has_key(key)的替代,现在必须使用key in d。
在Python 2中,字典方法keys、values和items返回列表。在Python 3中,它们返回视图对象;视图对象不是迭代器,它们与迭代器有两点不同,即:
- 它们有大小(可以使用
len函数) - 它们可以多次迭代
此外,与迭代器一样,字典中的更改会反映在视图对象中。
Python 2.7从Python 3中回退了这些方法;它们分别可用作viewkeys、viewvalues和viewitems。要将Python 2代码转换为Python 3代码,相应的形式是:
- Python 2中的
d.keys()、d.values()和d.items()应更改为list(d.keys())、list(d.values())和list(d.items()) - Python 2中的
d.iterkeys()、d.itervalues()和d.iteritems()应更改为iter(d)、iter(d.values())和iter(d.items()) - 最后,Python 2.7中的方法调用
d.viewkeys()、d.viewvalues()和d.viewitems()可以替换为d.keys()、d.values()和d.items()
将Python 2代码转换为Python 3代码时,有时会比较棘手,尤其是在迭代字典的键、值或项时进行修改。考虑以下代码:
d = {'a': 0, 'b': 1, 'c': 2, '!': 3}
for key in d.keys():
if key.isalpha():
del d[key]
代码看起来像是在Python 3中也会类似地工作,但在这里,keys方法返回的是视图对象,而不是列表,如果在迭代过程中字典大小发生变化,Python 3代码将因RuntimeError而崩溃:在迭代过程中字典大小发生了变化。解决方案当然是正确地写成for key in list(d)。
同样,视图对象的行为与迭代器不同:不能在它们上使用next(),并且不能恢复迭代;相反,它会重新开始;如果Python 2代码将d.iterkeys()、d.itervalues()或d.iteritems()的返回值传递给一个期望迭代器而不是可迭代对象的方法,那么在Python 3中应该是iter(d)、iter(d.values())或iter(d.items())。
Section 149.28: 类布尔值
Python 2.x Version ≤ 2.7
在Python 2中,如果你想自己定义类的布尔值,你需要在你的类中实现__nonzero__方法。默认值为True。
class MyClass:
def __nonzero__(self):
return False
my_instance = MyClass()
print bool(MyClass) # True
print bool(my_instance) # False
Python 3.x Version ≥ 3.0
在Python 3中,使用__bool__而不是__nonzero__。
class MyClass:
def __bool__(self):
return False
my_instance = MyClass()
print(bool(MyClass)) # True
print(bool(my_instance)) # False
Section 149.29: Python 2中hasattr函数的错误
在Python 2中,当属性引发错误时,hasattr会忽略该属性,返回False。
class A(object):
@property
def get(self):
raise IOError
class B(object):
@property
def get(self):
return 'get in b'
a = A()
b = B()
print 'a hasattr get: ', hasattr(a, 'get')
# output False in Python 2 (fixed, True in Python 3)
print 'b hasattr get', hasattr(b, 'get')
# output True in Python 2 and Python 3
此错误已在Python 3中修复。因此,如果你使用的是Python 2,可以使用以下代码:
try:
a.get
except AttributeError:
print("no get property!")
或者使用getattr代替:
p = getattr(a, "get", None)
if p is not None:
print(p)
else:
print("no get property!")