pythonpython-3.5python-typing

Is there a strategy for making Python 3.5 code with type-annotations backwards compatible?


I want to support new Python features in my open-source libraries. Python's new type-hinting makes it easier for users to use my software.

But it comes with a snag - it relies on a library called typing for some of the more interesting type annotations. That library doesn't exist in Python < 3.5.

Normally I'd handle that using a compatibility library (e.g. six), however there's no support for the typing module in six yet.

Another acceptable solution might be something like a 3to2 converter which can strip away the unsupported features. Unfortunately I've not yet seen a 3.5 to 3.(x<5) converter.

It seems that the only alternative available right now would be to wrap all my typedef imports into try-blocks and provide a fake typedef for the older versions of the language. That's ugly and not really the way I want to take my project.

Any suggestions?


Solution

  • Type hinting in Python 3.5 consists of two parts:

    Both can be used in earlier Python versions, or can be made to work where the annotation syntax is not yet supported.

    The module has been backported to Python 3.2 and newer. Annotations have been supported by all Python 3 versions, right from 3.0 onwards, see PEP 3107. That means type-hinted code can work for all widely-used Python 3 distributions.

    For Python 2.x, you can use stub files instead; these are not actually executed and only the static analysis tool needs to be able to parse these. You'd still 'import' the typing module for these, but the module is never actually loaded, nor does it need to be installed for stub files. Stub files have the .pyi extension and live next to their .py counterparts, but include the full annotation, but no function bodies (you shoud use the ... ellipsis literal instead).

    You could look at the Mypy stub specifications for how this'll work in practice; the Python type hinting PEP was largely inspired by tools like Mypy.