为Python模块推荐"仅Python 3"兼容性的标准方法是什么?

Dhr*_*hak 4 python python-2.7 python-3.x

有一个python代码,应该支持Python 3,但可能会也可能不会在Python 2.7中运行.例如,这个代码段可以在Python 2.7和Python 3中运行.即使代码在Python 2.7上运行良好,在严格模式下强制执行和推荐Python 3兼容性的标准方法是什么?

print('This file works in both')
print('How to throw an exception,and suggest recommendation of python 3 only ?')
Run Code Online (Sandbox Code Playgroud)

Python 2.7:https://ideone.com/bGnbvd

Python 3.5:https://ideone.com/yrTi3p

可能存在多个hacks和异常,它们在Python 3中工作,而不是在Python 2.7中,可用于实现此目的.我正在寻找文件/模块/项目开头的最佳推荐方法.

ale*_*cxe 11

如果它是一个合适的Python包setup.py,你可以使用几件事:

  • python_requires 分类

    如果您的项目仅在某些Python版本上运行,则将python_requires参数设置为适当的PEP 440版本说明符字符串将阻止pip在其他Python版本上安装项目.

    样品: python_requires='>=3',

  • 由于python_requires最近添加了对分类器的支持,因此您应考虑使用旧版本的pip和安装软件包的用户setuptools.在这种情况下,您可以像Django一样检查文件sys.version_info内部:setup.py

    import sys
    
    CURRENT_PYTHON = sys.version_info[:2]
    REQUIRED_PYTHON = (3, 5)
    
    # This check and everything above must remain compatible with Python 2.7.
    if CURRENT_PYTHON < REQUIRED_PYTHON:
        sys.stderr.write("""...""")
        sys.exit(1)
    
    Run Code Online (Sandbox Code Playgroud)
  • Programming LanguagePython版本分类器:

    'Programming Language :: Python',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
    'Programming Language :: Python :: 3 :: Only',
    
    Run Code Online (Sandbox Code Playgroud)

并且,作为奖励,如果包通过PyPI包索引分发,python_requires并且其他分类器将显示在包主页上.


Chr*_*nds 7

你可以简单地检查一下sys.version_info:

import sys
if sys.version_info[0] < 3:
    raise SystemExit("Use Python 3 (or higher) only")
Run Code Online (Sandbox Code Playgroud)