Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python convention for specifying compatible interpreter versions?

Similarly to the __author__ or __version__ top level module variables, is there any convention for specifying supported Python versions for a Python source file?

My usecase is a project that has some scripts that need to be compatible with Python 2.4. I would like to note that fact in them in some universally recognizable way.

I am not asking how to require a minimal Python version during execution. My problem is that developers may accidentally use feature which is not compatible with python version this particular script needs to support. PyCharm can warn about Python incompatibilities. It would be great if it could pick up this annotation and configure the warning on a per-file basis.

like image 682
user7610 Avatar asked Nov 17 '16 21:11

user7610


1 Answers

There's no convention that I know of for specifying supported Python versions in a Python source file. If you're making a Python library and distributing it via PyPI (and pip), you can add package metadata that says which versions of Python it's compatible with.

For example, for my scandir module, you can see on PyPI that it's (currently) marked as compatible with Python 2.6, 2.7, and 3.2-3.5. That metadata lives in the classifiers keyword in the package's setup.py:

setup(
    name='scandir',
    # ...
    classifiers=[
        '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',
        'Programming Language :: Python :: 3.5',
        # ...
    ]
)

If you're not releasing this as a PyPI package, one alternative might be to produce a warning when the module is imported on an older version of Python, saying that the FizzBuzz feature isn't supported on this version of Python.

import sys, warnings
if sys.version_info < (3, 5):
    warnings.warn('The FizzBuzz feature is only supported on Python 3.5+')

All that said, personally I'd just keep it simple: document that feature X is only supported on Python 3.5+ and then if someone tries to use that feature on an older version, just let it fail.

like image 138
Ben Hoyt Avatar answered Nov 08 '22 11:11

Ben Hoyt