Type Annotations

Python 3.5 introduced type annotations into the language, and Python 3.6 expanded on them. While still optional, using static types (and checking them) can help avoid some of the dangers of using dynamic type systems.

Type annotations can be used on functions:

def return_plus_one(a: int) -> int:
    return a + 1

And on variables:

my_str: str = 'foobar'

As noted above, this typing is completely optional. However, now a static analysis program like mypy can check types and throw errors if you are violating the speciied typing. For example, given this file:

#!/usr/bin/env python3

def return_plus_one(a: int) -> int:
    return a + 1

x: str = return_plus_one(1)

Mypy will raise an error about the unsafe typing:

chris@maxima $ mypy run.py 
run.py:6: error: Incompatible types in assignment (expression has type "int", variable has type "str")
chris@maxima $

It will also warn about lacking return types:

#!/usr/bin/env python3

foobar = print('barfoo')

chris@maxima (dot-emacs-testing) ∑ mypy run.py 
run.py:3: error: "print" does not return a value
chris@maxima (dot-emacs-testing) ∑