Python is dynamic typed language, but static type variable can be possible if we use type annotations. Python 3.5 and later versions have functionality of type hinting. Though It is completely optional.
Type hinting is useful for testing purpose in CI. It does not change code to static variable; but it make easy to understand code that you have written long time ago.
Simple example of type hinting:
Let’s see following funtion,
Above code indicate that
addme() takes 2 integer parameters (a and
b) and returns int value.
-> symbol shows return value type.
Mypy is a static type checker. To install it from PyPI run:
Once Mypy is installed, we can check types using following command,
There is no any output if types are correct as per type annotations given in code.
In an example of
addme(), if we change to
addme(4, "a") and run
mypy. It shows error as,
For this we need to import the following:
Let’s look at an example of type hinting for List, Dict and Tuple,