编写兼容 python 2.7 和 3.5+ 的代码
编写新的代码最好不要再兼容 Python 2.6 及以下版本了,坑太多。兼容 2.7 就足够了。同样地,Python 3.5 及以下版本的坑也很多,Python 3 最好从 3.5 开始兼容。
导入模块
Python 3 默认绝对导入,Python 2 默认相对导入。所以代码第一行就应写上:
pythonfrom __future__ import absolute_import
异常处理
Python 2 和 3 异常处理语句有所差异,应使用新的异常处理语句:
pythontry:
raise ValueError('value error')
except ValueError as e
pass
显式继承新式类
Python 3 默认使用新式类, 代码显式继承新式类实现兼容:
pythonclass Foo(object):
pass
print() 代替 print
Python 2 中 print 是语句,Python 3 中的 print 是函数。
pythonfrom __future__ import print_function
print('Hello', 'World')
注意重命名的库
Python 3 中的一些库名已经更名,需要手动添加代码实现兼容:
pythontry:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
try:
from itertools import izip as zip
except ImportError:
pass
try:
from io import BytesIO as StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
import cPickle as pickle
except ImportError:
import pickle
try:
range = xrange
except NameError:
range = range
使用兼容库
shellpip install future
pip install six
如果不打算支持 Python 2.7 以下版本,six库的意义不大。
使用内置 next() 函数
迭代器的 next()
方法变成 __next__()
了。使用内置 next()
函数进行遍历。
整数除法
Python 2 中的 /
除法是整数除法,Python 3 中则需要使用 //
来实现整数除法。为了实现兼容,开启 Python 2 的浮点除法功能:
pythonfrom __future__ import division
assert 3 / 2 == 1.5
字符串处理
字符串类型判断:
isinstance(s, basestring)
用isinstance(s, string_types)
代替;isinstance(s, unicode)
用isinstance(s, text_type)
代替;isinstance(s, str)
要获取bytes
类型,用isinstance(s, bytes)
或isinstance(s, (bytes, bytearray))
代替。
默认使用 Unicode 字符串:
pythonfrom __future__ import unicode_literals
使用 io.open 代替内置函数 open
Python 3 中的 io.open()
是 内置 open()
函数的别名。
八进制
使用 Python 2 和 3 兼容的八进制表示方法:
python0o777
字典迭代
Python 3 中取消了字典对象的 iterkeys()
、 itervalues()
和 iteritems()
方法。
pythonfor (key, value) in dictionary.items():
pass
for key in dictionary.keys():
pass
for key in dictionary:
pass
for value in dictionary.values():
pass