XD blog

blog page

annotation, mypy, python, static typing


2014-08-20 Python, Annotation, Type Checking, mypy

Python is interpreted at runtime. Variables types are discovered during the execution. That is also why it is so slow. It is difficult to anticipate what the type of variable will be even though projects such as pypy or nuitka aims at compiling a python script by doing so. They must do type infering. Python 3 has introduced a nice feature which helps doing that: function annotations. It specifies a static type to the parameters and/or the returned result. By doing this, it is easier to check types at runtime (with module typecheck-decorator):

from typecheck import typecheck

@typecheck
def p(i:int) :
    print('hello',i)

@typecheck
def inc(x) -> int :
    return x+1

a = p(5)    # no error
a = p(5.5)  # error

inc(1)      # no error
inc(1.1)    # error

You can also check complex types such as dictionary of string.

from typecheck import typecheck
import typecheck as tc

@typecheck
def count(text:str)->tc.dict_of(str, int):
    words = text.split()
    res = { }
    for w in words:
        res [ w ] = res.get(w,0) + 1
    res[None] = 0  # will cause an error while checking the returned value
    return res
    
count("a b c a")  # raises an exception

The other initiative based on the annotations is mypy. It is a static compiler which leverages annotations to avoid infering types. It is scheduled to be released next year.


<-- -->

Xavier Dupré