Python 2.7.x 與 Python 3.x 的不同點

本文翻譯自:《Key differences between Python 2.7.x and Python 3.x》

許多 Python 初學者想知道他們應該從 Python 的哪個版本開始學習。對于這個問題我的答案是 “你學習你喜歡的教程的版本,然后檢查他們之間的不同。” 但如果你并未了解過兩個版本之間的差異,個人推薦使用 Python 2.7.x 版本,畢竟大部分教材等資料還是用Python 2.7.x來寫的。

但是如果你開始一個新項目,并且有選擇權?我想說的是目前沒有對錯,只要你計劃使用的庫 Python 2.7.x 和 Python 3.x 雙方都支持的話。盡管如此,當在編寫它們中的任何一個的代碼,或者是你計劃移植你的項目的時候,是非常值得看看這兩個主要流行的 Python 版本之間的差別的,以便避免常見的陷阱。


1 __future__模塊

Python 3.x 介紹的 一些Python 2 不兼容的關鍵字和特性可以通過在 Python 2 的內置__future__ 模塊導入。如果你計劃讓你的代碼支持 Python 3.x,建議你使用 __future__模塊導入。例如,如果我想要 在Python 2 中表現(xiàn) Python 3.x 中的整除,我們可以通過如下導入:

from __future__ import division

更多的 future 模塊可被導入的特性被列在下表中:


(來源: https://docs.python.org/2/library/future.html


2 print函數(shù)

很瑣碎,而print語法的變化可能是最廣為人知的了,但是仍值得一提的是: Python 2 的 print 聲明已經被 print()函數(shù)取代了,這意味著我們必須包裝我們想打印在小括號中的對象。
Python 2 不具有額外的小括號問題。但對比一下,如果我們按照 Python 2 的方式不使用小括號調用print 函數(shù),Python 3 將拋出一個語法異常(SyntaxError)。

Python 2

print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'

運行結果如下:

Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

print('Python', python_version())
print('Hello, World!')
print("some text,", end="") 
print(' print more text on the same line')

運行結果如下:

Python 3.4.1
Hello, World!
some text, print more text on the same line

Python 3

print 'Hello, World!'

運行結果如下:

File ““, line 1
  print ‘Hello, World!’
          ^
SyntaxError: invalid syntax

以上通過 Python 2 使用 Printing "Hello, World" 是非常正常的,盡管如此,如果你有多個對象在小括號中,我們將創(chuàng)建一個元組,因為print 在 Python 2 中是一個聲明,而不是一個函數(shù)調用。

print 'Python', python_version()
print('a', 'b')
print 'a', 'b'

運行結果如下:

Python 2.7.7
(‘a’, ‘b’)
a b

3 整除

如果你正在移植代碼,這個變化是特別危險的。或者你在 Python 2 上執(zhí)行 Python 3 的代碼。因為這個整除的變化表現(xiàn)在它會被忽視(即它不會拋出語法異常)。

因此,我還是傾向于使用一個float(3)/23/2.0代替在我的 Python 3 腳本保存在 Python 2 中的 3/2的一些麻煩(并且反而過來也一樣,我建議在你的 Python 2 腳本中使用 from __future__ import division)。

Python 2

print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0

運行結果如下:

Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

print('Python', python_version())
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)

運行結果如下:

Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

4 Unicode

Python 2 有 ASCII str() 類型,unicode()是單獨的,不是 byte 類型。
現(xiàn)在, 在 Python 3,我們最終有了 Unicode (utf-8)字符串,以及一個字節(jié)類:bytebytearrays。

Python 2

print 'Python', python_version()

運行結果如下:

Python 2.7.6
print type(unicode('this is like a python3 str type'))

運行結果如下:

< type ‘unicode’ >
print type(b'byte type does not exist')

運行結果如下:

< type ‘str’ >
print 'they are really' + b' the same'

運行結果如下:

they are really the same
print type(bytearray(b'bytearray oddly does exist though'))

運行結果如下:

< type ‘bytearray’ >

Python 3

print('Python', python_version())
print('strings are now utf-8 \u03BCnico\u0394é!')

運行結果如下:

Python 3.4.1
strings are now utf-8 μnicoΔé!
print('Python', python_version(), end="")
print(' has', type(b' bytes for storing data'))

運行結果如下:

Python 3.4.1 has < class ‘bytes’ >
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))

運行結果如下:

and Python 3.4.1 also has < class ‘bytearray’>

5 xrange模塊

在 Python 2 中xrange()創(chuàng)建迭代對象的用法是非常流行的。比如: for循環(huán)或者是列表/集合/字典推導式。
  
這個表現(xiàn)十分像生成器(比如?!岸栊郧笾怠保?。但是這個 xrange-iterable是無窮的,意味著你可以無限遍歷。
  
由于它的惰性求值,如果你不得僅僅不遍歷它一次,xrange() 函數(shù) 比range()更快(比如 for 循環(huán))。盡管如此,對比迭代一次,不建議你重復迭代多次,因為生成器每次都從頭開始。
  
在 Python 3 中,range()是像 xrange() 那樣實現(xiàn)以至于一個專門的 xrange()函數(shù)都不再存在(在 Python 3 中xrange()會拋出命名異常)。

import timeit
n = 10000
def test_range(n):
    return for i in range(n):
        pass
def test_xrange(n):
    for i in xrange(n):
        pass

Python 2

print 'Python', python_version()
print '\ntiming range()'
%timeit test_range(n)
print '\n\ntiming xrange()'
%timeit test_xrange(n)

運行結果如下:

Python 2.7.6
timing range()
1000 loops, best of 3: 433 μs per loop
timing xrange()
1000 loops, best of 3: 350 μs per loop

Python 3

print('Python', python_version())
print('\ntiming range()')
%timeit test_range(n)

運行結果如下:

Python 3.4.1
timing range()
1000 loops, best of 3: 520 μs per loop
print(xrange(10))

運行結果如下:

NameError Traceback (most recent call last)
in ()
——> 1 print(xrange(10))
NameError: name ‘xrange’ is not defined

6 Python3中的range對象的__contains__方法

另外一件值得一提的事情就是在 Python 3 中range有一個新的__contains__方法(感謝 Yuchen Ying 指出了這個),__contains__方法可以加速 “查找” 在 Python 3.x 中顯著的整數(shù)和布爾類型。

x = 10000000
def val_in_range(x, val):
    return val in range(x)
def val_in_xrange(x, val):
    return val in xrange(x)
print('Python', python_version())
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_range(x, x/2)
%timeit val_in_range(x, x//2)

運行結果如下:

Python 3.4.1
1 loops, best of 3: 742 ms per loop
1000000 loops, best of 3: 1.19 μs per loop

基于以上的 timeit 的結果,當它使一個整數(shù)類型,而不是浮點類型的時候,你可以看到執(zhí)行查找的速度是 60000 倍快。盡管如此,因為 Python 2.x 的range 或者是xrange 沒有一個__contains__ 方法,這個整數(shù)類型或者是浮點類型的查詢速度不會相差太大。

print 'Python', python_version()
assert(val_in_xrange(x, x/2.0) == True)
assert(val_in_xrange(x, x/2) == True)
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_xrange(x, x/2.0)
%timeit val_in_xrange(x, x/2)
%timeit val_in_range(x, x/2.0)
%timeit val_in_range(x, x/2)

運行結果如下:

Python 2.7.7
1 loops, best of 3: 285 ms per loop
1 loops, best of 3: 179 ms per loop
1 loops, best of 3: 658 ms per loop
1 loops, best of 3: 556 ms per loop

下面說下__contain__方法并沒有加入到 Python 2.x 中的證據(jù):

print('Python', python_version())
range.__contains__

運行結果如下:

Python 3.4.1
< slot wrapper ‘contains‘ of ‘range’ objects >
print 'Python', python_version()
range.__contains__

運行結果如下:

Python 2.7.7
AttributeError Traceback (most recent call last)
< ipython-input-7-05327350dafb> in < module>()
1 print ‘Python’, pythonversion()
——> 2 range.`_contains`
AttributeError: ‘builtinfunctionor_method’ object has no attribute `’__contains‘`
print 'Python', python_version()
xrange.__contains__

運行結果如下:

Python 2.7.7
AttributeError Traceback (most recent call last)
< ipython-input-8-7d1a71bfee8e> in < module>()
1 print ‘Python’, pythonversion()
——> 2 xrange.`_contains`
AttributeError: type object ‘xrange’ has no attribute '__contains__'

注意在 Python 2 和 Python 3 中速度的不同
有些人指出了 Python 3 的 range() 和 Python 2 的 xrange() 之間的速度不同。因為他們是用相同的方法實現(xiàn)的,因此期望相同的速度。盡管如此,這事實在于 Python 3 傾向于比 Python 2 運行的慢一點。

def test_while():
    i = 0
    while i < 20000:
        i += 1
    return

Python 3

print('Python', python_version())
%timeit test_while()

運行結果如下:

Python 3.4.1
100 loops, best of 3: 2.68 ms per loop

Python 2

print 'Python', python_version()
%timeit test_while()

運行結果如下:

Python 2.7.6
1000 loops, best of 3: 1.72 ms per loop

7 拋出異常

Python 2 接受新舊兩種語法標記,在 Python 3 中如果我不用小括號把異常參數(shù)括起來就會阻塞(并且反過來引發(fā)一個語法異常)。
Python 2

print 'Python', python_version()

運行結果如下:

Python 2.7.6
raise IOError, "file error"

運行結果如下:

IOError Traceback (most recent call last)
< ipython-input-8-25f049caebb0> in < module>()
——> 1 raise IOError, “file error”
IOError: file error
raise IOError("file error")

運行結果如下:

IOError Traceback (most recent call last)
< ipython-input-9-6f1c43f525b2> in < module>()
——> 1 raise IOError(“file error”)
IOError: file error

Python 3

print 'Python', python_version()

運行結果如下:

Python 3.4.1
raise IOError, "file error"

運行結果如下:

File ““, line 1
raise IOError, “file error”
      ^
SyntaxError: invalid syntax

在 Python 3 中,可以這樣拋出異常:

print('Python', python_version())
raise IOError("file error")

運行結果如下:

Python 3.4.1
OSError Traceback (most recent call last)
< ipython-input-11-c350544d15da> in < module>()
1 print(‘Python’, python_version())
——> 2 raise IOError(“file error”)
OSError: file error

8 處理異常

在 Python 3 中處理異常也輕微的改變了,在 Python 3 中我們現(xiàn)在使用 as 作為關鍵詞。
Python 2

print 'Python', python_version()
try:
    let_us_cause_a_NameError
except NameError, err:
    print err, '--> our error message'

運行結果如下:

Python 2.7.6
name ‘let_us_cause_a_NameError’ is not defined —> our error message

Python 3

print('Python', python_version())
try:
    let_us_cause_a_NameError
except NameError as err:
    print(err, '--> our error message')

運行結果如下:

Python 3.4.1
name ‘let_us_cause_a_NameError’ is not defined —> our error message

9 next()函數(shù)和.next()方法

因為 next() (.next())是一個如此普通的使用函數(shù)(方法),這里有另外一個語法改變(或者是實現(xiàn)上改變了),值得一提的是:在 Python 2.7.5 中函數(shù)和方法你都可以使用,next()函數(shù)在 Python 3 中一直保留著(調用.next()拋出屬性異常)。
Python 2

print 'Python', python_version()
my_generator = (letter for letter in 'abcdefg')
next(my_generator)
my_generator.next()

運行結果如下:

Python 2.7.6
‘b

Python 3

print('Python', python_version())
my_generator = (letter for letter in 'abcdefg')
next(my_generator)

運行結果如下:

Python 3.4.1
‘a’
1
my_generator.next()

運行結果如下:

AttributeError Traceback (most recent call last)
< ipython-input-14-125f388bb61b> in < module>()
——> 1 my_generator.next()
AttributeError: ‘generator’ object has no attribute ‘next’

10 For循環(huán)變量和全局命名空間泄漏

好消息:在 Python 3.x 中for循環(huán)變量不會再導致命名空間泄漏。
  
在 Python 3.x 中做了一個改變,在 What’s New In Python 3.0 中有如下描述:
  
“列表推導不再支持[... for var in item1, item2, ...] 這樣的語法。使用[... for var in (item1, item2, ...)]代替。也需要提醒的是列表推導有不同的語義: 他們關閉了在list()構造器中的生成器表達式的語法糖, 并且特別是循環(huán)控制變量不再泄漏進周圍的作用范圍域。

Python 2

print 'Python', python_version()
i = 1
print 'before: i =', i
print 'comprehension: ', [i for i in range(5)]
print 'after: i =', i

運行結果如下:

Python 2.7.6
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 4

Python 3

print('Python', python_version())
i = 1
print('before: i =', i)
print('comprehension:', [i for i in range(5)])
print('after: i =', i)

運行結果如下:

Python 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1

11 比較不可排序類型

在 Python 3 中的另外一個變化就是當對不可排序類型做比較的時候,會拋出一個類型錯誤。
Python 2

print 'Python', python_version()
print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
print "(1, 2) > 'foo' = ", (1, 2) > 'foo'
print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)

運行結果如下:

Python 2.7.6
[1, 2] > ‘foo’ = False
(1, 2) > ‘foo’ = True
[1, 2] > (1, 2) = False

Python 3

print('Python', python_version())
print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))

運行結果如下:

Python 3.4.1
TypeError Traceback (most recent call last)
< ipython-input-16-a9031729f4a0> in < module>()
1 print(‘Python’, python_version())
——> 2 print(“[1, 2] > ‘foo’ = “, [1, 2] > ‘foo’)
3 print(“(1, 2) > ‘foo’ = “, (1, 2) > ‘foo’)
4 print(“[1, 2] > (1, 2) = “, [1, 2] > (1, 2))
TypeError: unorderable types: list() > str()

12 通過input()解析用戶的輸入

幸運的是,在 Python 3 中已經解決了把用戶的輸入存儲為一個 str對象的問題。為了避免在 Python 2 中的讀取非字符串類型的危險行為,我們不得不使用raw_input()代替。
Python 2

>>> my_input = input('enter a number: ')
enter a number: 123
>>> type(my_input)
<type 'int'>
>>> my_input = raw_input('enter a number: ')
enter a number: 123
>>> type(my_input)
<type 'str'>

Python 3

>>> my_input = input('enter a number: ')
enter a number: 123
>>> type(my_input)
<class 'str'>

13 返回可迭代對象,而不是列表

如果在 xrange 章節(jié)看到的,現(xiàn)在在 Python 3 中一些方法和函數(shù)返回迭代對象 — 代替 Python 2 中的列表
  
因為我們通常那些遍歷只有一次,我認為這個改變對節(jié)約內存很有意義。盡管如此,它也是可能的,相對于生成器 —- 如需要遍歷多次。它是不那么高效的。
  
而對于那些情況下,我們真正需要的是列表對象,我們可以通過list()函數(shù)簡單的把迭代對象轉換成一個列表。
Python 2

print 'Python', python_version() 
print range(3) 
print type(range(3))

運行結果如下:

Python 2.7.6
[0, 1, 2]
< type ‘list’>

Python 3

print('Python', python_version())
print(range(3))
print(type(range(3)))
print(list(range(3)))

運行結果如下:

Python 3.4.1
range(0, 3)
< class ‘range’>
[0, 1, 2]

在 Python 3 中一些經常使用到的不再返回列表的函數(shù)和方法:

  • zip()
  • map()
  • filter()
  • 字典的.keys()方法
  • 字典的.values()方法
  • 字典的.items()方法

更多的關于 Python 2 和 Python 3 的文章

移植到 Python 3
Should I use Python 2 or Python 3 for my development activity?
What’s New In Python 3.0
Porting to Python 3
Porting Python 2 Code to Python 3
How keep Python 3 moving forward

Python 3 的擁護者和反對者
10 awesome features of Python that you can’t use because you refuse to upgrade to Python 3
Everything you did not want to know about Unicode in Python 3
Python 3 is killing Python
Python 3 can revive Python
Python 3 is fine

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容