Python static typing

Posted on Sun 26 June 2016 in misc

Normally in Python if you create a variable i as an integer, you can later assign a a string value. i just points to some data of some type in memory and can be re-assigned at will.

This can make it hard to reason about code. Is the input to this function a float or an integer? A list or an array?

With static typing a variable can't change its type and it can make reasoning about some code easier. If you know that i is an integer and you know that no-matter what, it will never become a float, then you can always use i as an index. With true static typing, you will even get an error if you try and change i.

In Python you can annotate type and you can have a script check if these annotations are violated at any point in code, as a sort of pre-execution sanity check.

Here is how it works:

from typing import List

def myfunction(list_of_int:List[int], floatingpoint:float) -> bool:
    """ This function takes a list of integers and a
    floating point number and returns a boolean """
    return True

links: