python 2 and 3 compatible

2000: python2
2008: python3
2010: python2.7
2020: python2.7 end of life

python3 new things

ipaddress
venv
asyncio
unicode

future

from __future__ import absolute_import, division, generators, unicode_literals, print_function, nested_scopes, with_statement

The __future__ statement is not a import statement, it must be put at the very top.
After import the _future__, we can use new features in old version of python.
The above listed future remains the same in python2.7 and python3.

First, we import all these future and make it work in python2. Then we port it to python3.

str, bytes, unicode

In python2, str and bytes are the same, and they are different from unicode.

>>> type(bytes('a'))
<type 'str'>
>>> type(str('a'))
<type 'str'>
>>> type(u'a')
<type 'unicode'>

In python3, they are different. str is unicode by default, and bytes is binary data. (bytearray is mutable bytes.)
Unicode is a type of character encoding(or "character map", "character set", they have the same meaning).
UTF-8 is Unicode Transformation Format. If UTF-8 is a train, then unicode is the payloads.

An example in python3, convert between bytes and unicode string

>>> cd = '成都'
>>> byte_utf8 = cd.encode('utf-8')
>>> byte_utf8
b'\xe6\x88\x90\xe9\x83\xbd'
>>> byte_gb = cd.encode('gb2312')
>>> byte_gb
b'\xb3\xc9\xb6\xbc'
>>> byte_utf8.decode('utf-8')
'成都'
>>> byte_gb.decode('gb2312')
'成都'

In python2.7, importing unicode_literals will set default string type to unicode.

>>> a = 'aa'
>>> type(a)
<type 'str'>
>>> from __future__ import unicode_literals
>>> a = 'aa'
>>> type(a)
<type 'unicode'>
>>> type(str(a))
<type 'str'>

Importing unicode_literals does NOT change the str type, it only makes the new created string object as a unicode type.
So don't use str() to convert object. Instead, use unicode().
But there is no unicode() in python3, to make it compatible with python3, add the following code.

import sys
if sys.version_info >= (3, 0):
    def unicode(*args, **kwargs):
        return str(*args, **kwargs)

And there is another issue, in python3, convert bytes to str will let the b mark left.
And convert data with bytes() is also different.

>>> b = b'bbb'
>>> str(b)
"b'bbb'"

In python3, some network libs may use bytes as input/output data type, such as telnetlib and paramiko.
So you may need to convert the type from/to unicode.
It's suggested to use the following functions, they work in both python2 and python3.

def to_unicode(data):
    if isinstance(data, (bytes, bytearray)):
        return data.decode('utf-8')
    else:
        return unicode(data)

def to_bytes(data):
    if sys.version_info >= (3, 0):
        return bytes(data, 'utf-8')
    else:
        return bytes(data)

safer relative import

Suppose the package is:

mypackage/
    __init__.py
    submodule1.py
    submodule2.py

and the code below is in submodule1.py:

# Python 2 only:
import submodule2
# Python 2 and 3:
from . import submodule2
# Python 2 and 3:
# To make Py2 code safer (more like Py3) by preventing
# implicit relative imports, you can also add this to the top:
from __future__ import absolute_import

print

In python3, there is no print keyword, only print() function.
After from __future__ import print_function, the print "xx" in python2 will raise Exception.
So always use print().

division

python2

>>> 5 / 2
2
>>> 5 // 2
2

python3

>>> 5 / 2
2.5
>>> 5 // 2
2

After from __future__ import division, the python2 action is the same as python3.
It's better to always use //.

exception

Work both in python 2 and 3:

def test():
    raise Exception('exception in test')

try:
    test()
except Exception as e:
    print(str(e))

iterable objects instead of lists

Some methods returning lists in python2 has changed to returning iterable objects in python3.

range()
dict.keys()
dict.values()
dict.items()
map()
filter()

range() and xrange()

The xrange() in python2 has changed to range() in python3.

import sys
if sys.version_info >= (3, 0):
    def xrange(*args, **kwargs):
        return iter(range(*args, **kwargs))

Don't use xrange(), always use range().

next() function and .next() method

Always use next() function, no .next() method in python3.

>>> my_generator = (letter for letter in 'abcdefg')
>>> next(my_generator)
'a'
>>> next(my_generator)
'b'

for loop namespace

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

In python2, i=4 after the for loop, but in python3, i=1.
So don't use global variable as the for variable.

other modules

try:
    import queue
    from urllib.parse import urlparse, urlencode
    from urllib.request import urlopen, Request
    from urllib.error import HTTPError
except ImportError:
    import Queue as queue
    from urlparse import urlparse
    from urllib import urlencode
    from urllib2 import urlopen, Request, HTTPError

reference

How To Port Python 2 Code to Python 3
https://www.digitalocean.com/community/tutorials/how-to-port-python-2-code-to-python-3

The key differences between Python 2.7.x and Python 3.x with examples
http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html

Writing code that runs under both Python2 and 3
https://wiki.python.org/moin/PortingToPy3k/BilingualQuickRef

Cheat Sheet: Writing Python 2-3 compatible code
http://python-future.org/compatible_idioms.html

What's REALLY New in Python 3
https://powerfulpython.com/blog/whats-really-new-in-python-3/

Unicode HOWTO
https://docs.python.org/3/howto/unicode.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末失暴,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子讹剔,更是在濱河造成了極大的恐慌颅眶,老刑警劉巖蜈出,帶你破解...
    沈念sama閱讀 211,042評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異涛酗,居然都是意外死亡铡原,警方通過查閱死者的電腦和手機(jī)偷厦,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評論 2 384
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來燕刻,“玉大人只泼,你說我怎么就攤上這事÷严矗” “怎么了请唱?”我有些...
    開封第一講書人閱讀 156,674評論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長过蹂。 經(jīng)常有香客問我十绑,道長,這世上最難降的妖魔是什么酷勺? 我笑而不...
    開封第一講書人閱讀 56,340評論 1 283
  • 正文 為了忘掉前任本橙,我火速辦了婚禮,結(jié)果婚禮上鸥印,老公的妹妹穿的比我還像新娘。我一直安慰自己坦报,他們只是感情好库说,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,404評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著片择,像睡著了一般潜的。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上字管,一...
    開封第一講書人閱讀 49,749評論 1 289
  • 那天啰挪,我揣著相機(jī)與錄音,去河邊找鬼嘲叔。 笑死亡呵,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的硫戈。 我是一名探鬼主播锰什,決...
    沈念sama閱讀 38,902評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼丁逝!你這毒婦竟也來了汁胆?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,662評論 0 266
  • 序言:老撾萬榮一對情侶失蹤霜幼,失蹤者是張志新(化名)和其女友劉穎嫩码,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體罪既,經(jīng)...
    沈念sama閱讀 44,110評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡铸题,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年铡恕,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片回挽。...
    茶點(diǎn)故事閱讀 38,577評論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡没咙,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出千劈,到底是詐尸還是另有隱情祭刚,我是刑警寧澤,帶...
    沈念sama閱讀 34,258評論 4 328
  • 正文 年R本政府宣布墙牌,位于F島的核電站涡驮,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏喜滨。R本人自食惡果不足惜捉捅,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,848評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望虽风。 院中可真熱鬧棒口,春花似錦、人聲如沸辜膝。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,726評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽厂抖。三九已至茎毁,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間忱辅,已是汗流浹背七蜘。 一陣腳步聲響...
    開封第一講書人閱讀 31,952評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留墙懂,地道東北人橡卤。 一個(gè)月前我還...
    沈念sama閱讀 46,271評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像损搬,于是被迫代替她去往敵國和親蒜魄。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,452評論 2 348

推薦閱讀更多精彩內(nèi)容