Search code examples
python

Explicitly typed version of Python?


I rather like Python's syntactic sugar; and standard library functions.

However the one feature which I dislike; is implicit typing.

Is there a distribution of Python with explicit typing; which is still compatible with e.g.: packages on PyPi?

[I was looking into RPython]


Solution

  • From python 3, the ability to use type annotation was introduced into the python standard with PEP 3017.

    Fast-forward to python 3.5 and PEP 0484 builds on this to introduce type hinting along with the typing module which enables one to specify the types for a variable or the return type of a function.

    from typing import Iterator
    
    def fib(n: int) -> Iterator[int]:
        a, b = 0, 1
        while a < n:
            yield a
            a, b = b, a + b
    

    Above example taken from https://pawelmhm.github.io

    According to the 484 notes:

    While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter. (While it would of course be possible for individual users to employ a similar checker at run time for Design By Contract enforcement or JIT optimization, those tools are not yet as mature.)

    tl;dr

    Although python provides this form of "static typing", it is not enforced at run time and the python interpreter simply ignores any type specifications you have provided and will still use duck typing to infer types. Therefore, it is up to you to find a linter which will detect any issues with the types.

    Furthermore

    The motivation for including typing in the python standard was mostly influenced by mypy, so it might be worth checking them out. They also provide examples which may prove useful.