写出兼容Python2和Python3的代码

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/

字符串字面量类型文本字节
python2unicodestr
python3strbytes
sixsix.text_typesix.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.详细内容

8.兼容python2和python3库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值