Types in Python

Categories: python clean code

Coming from languages like Java/C#, I found something missing in python.
I miss defining types for variables and methods.

Variables: Python vs Java

# Python Variables
name = "Tom"
cost = 5

// Java Variables
String name = "Tom"
int cost = 5

Methods: Python vs Java

# Python method

def add(a,b):
    return a + b
// Java method

public String add (String a, String b) {
    return a + b
}

What does the python version of the add function take? What does it return?

The add operator works for string, integers, list. Is that intended?

Some of the benefits of a language that supports types are:

  • documentation of inputs and outputs
  • capture error in wrong usage
  • better code completion with IDE

Luckily for us, with PEP484 python 3.6 supports types.

Variables: Typed
With built in primitive types, all that is needed

# Python Variables
name: str = "Tom"
cost: int = 5

For more complex types,

from typing import List, Set, Dict, Tuple, Optional

elements: List[int] = [1,2]
unique_elems: Set[int] = {6, 7}

scores: Dict[str, float] = {'user1': 2.0, 'user_2':5.2}


info: Tuple[int, str] = (2, "tom")

Methods: Typed

from typing import Union, List

def add_nums(a:int,b:int) -> int:
    return a + b

def add (a:Union[List,str,int],b:Union[List,str,int] ) -> [List,str,int] :
    return a +b

Example of defining own types

from typing import Tuple

LatLngType = Tuple[float, float]

point: LatLngType = (50.12, 70.21) 

Type Checking

Python doesn’t have anything built in the language that enforces types.
However there is mypy, a project from Dropbox.

Installation

pip install mypy

Running

mypy test.py

Consider this sample code. Do you see the error(s)?

Fig: python code with errors

Fig: python code with errors

Fig: Mypy output

Fig: Mypy output

Looking at the output, we see that we are wrongly:

  • forgot a return statement
  • accessing an attribute that doesn’t exist

At my work, we have started including types and mypy as part of our work. It has made our code base more maintainable.

See also