Static type checking in Python

Python is and will always remain a dynamically typed language. The dynamic nature of python makes the following code possible.

>>> a = 10
>>> type(a)
<class 'int'>
>>> a = "amalshaji"
>>> type(a)
<class 'str'>
>>> a = 3.14
>>> type(a)
<class 'float'>
def evaluate(a):
    print(f"The value is {a}")

evaluate(5)
evaluate("amalshaji")
❯ python test.py
The value is 5
The value is amalshaji

Python interpreter does type checking only when the code runs and the type of a variable is allowed to change over its lifetime.

PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.

Static type checking basically means you're telling the variable what they are supposed to hold. Let's tell the evaluate function that it should accept a of type int.

def evaluate(a: int):
    print(f"The value is {a}")

evaluate(5)
evaluate("amalshaji")
❯ python test.py
The value is 5
The value is amalshaji

It did not work?🤔

Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types. - 21 lines ago

For this task, we need to install a static type checker mypy

Install

python3 -m pip install -U mypy

# run the type check
mypy test.py
❯ mypy test.py
test.py:6: error: Argument 1 to "evaluate" has incompatible type "str"; expected "int"
Found 1 error in 1 file (checked 1 source file)

oopsie doopsie

The function return type can also be specified, using the -> operator.

def evaluate(a: int) -> int:
    return a + 10

For more types, you can use the typing module.

from typing import List, Tuple, Dict

def evaluate(a: List[int], b: Tuple[int], c: Dict[str, str]):
    pass

evaluate(a=[1, 2, 3], b=(4,), c={"name": "amalshaji", "description": "king"})
❯ mypy test.py
Success: no issues found in 1 source file

Advantages

  • The code is now partially documented with all the variable types listed.
  • IDE now knows what the variable type is, so better autocomplete.

    before.PNG

  • It'll help you read code better, especially the ones written by others.

PEP 484 defined how to add type hints to your Python code, based off work that Jukka Lehtosalo had done on his Ph.D. project—Mypy. The main way to add type hints is using annotations. As type checking is becoming more and more common, this also means that annotations should mainly be reserved for type hints.

Happy type checking

References

No Comments Yet