1.兼容范围
大部分情况下开源社区的约定俗成是支持Python 2.7以及3.4+
- 2.7以前的版本不兼容的部分较多,额外工作量太大且已经停止了更新支持
- 使用Python 2.7的人占了绝大多数,从投入产出上比较划算。
2.setup.py标记要兼容的版本
setup(
classifiers=[
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
]
)
3.兼容import
version detection
import sys
if sys.version_info[0] > 2:
from importlib import abc
else:
from importlib2 import abc
feature detection
try:
from importlib import abc
except ImportError:
from importlib2 import abc
4.__future__
# 使用python3的print函数,禁用python2的print语句
from __future__ import print_function
# 禁用python2字符串字面量类型
# Python2 str <--> Python3 bytes
# Python2 unicode <--> Python3 str
from __future__ import unicode_literal
# 像python3一样,int除以int得float,而不像Python2那样是整除
from __future__ import division
# 开启绝对导入
from __future__ import absolute_import
5.six
https://six.readthedocs.io/
字符串字面量类型 | 文本 | 字节 |
---|---|---|
python2 | unicode | str |
python3 | str | bytes |
six | six.text_type | six.binary_type |
import six
# 统一字符串变量类型判断
obj = ""
if isinstance(obj, six.text_type):
pass
# 统一 python2 raw_input和python3 input
from six.moves import input
6.兼容检测工具
- coverage.py——检测覆盖率(至少80%)
- pylint——分析Python代码中的错误,不符合代码风格标准
- caniusepython3——检测python3不支持的依赖
- Travis-CI——持续集成
- tox——通用的虚拟环境管理和测试命令行工具
- mypy, pytype——静态类型检查
- 2to3——python2到python3代码转化工具
7.详细内容
- Python官方迁移教程(Porting Python 2 Code to Python 3)
- Python官方兼容指南(Writing Python 2-3 compatible code )