How to Use Mypy to Type Check Your Python Programs
Type check your code in just a few seconds
Type hinting was called as the next big thing in Python a few years back. It was nothing but a simple solution to statically give the value type in the python code. Introduced in Python 3.5 and entered in PEP 484, type hinting allowed the programmers to give specific data type and get the output.
Like in the below function, the user is defining that the “name” argument must be of string type. Along with it, the return statement will also return a string.
def greeting(name: str) -> str:
return 'Hello ' + name
But, there was a catch in this type hinting phenomenon. In the below function, we expect the function to return string but it returns an integer here.
def greeting(name: str) -> str:
return 1print(greeting(“V”)) #output: 1
type(greeting(“V”)) #ouput: int
The program does work even though it doesn’t really output a string. Therefore, you will need an external program like a linter which type check your program and look at the code and tell whether the code is following the type annotation right or not.
mypy
mypy is a popular optional static type-checker program. After the inclusion of type hints in PEP 484 and Python, coders started using mypy to type check them statically. So, I am going to use it in our described case and type check our program.
Installing mypy using Terminal
python3 -m pip install mypy
After installing it, you can simply run your Python script using the below command.
mypy example.py
And, you will see output something like this. If there is some issue in your type hinting. In my case, the user expects that a string value will be returned. Instead, the function returned integer value.
Installing mypy plugin on IDEs
You can also install mypy on your IDEs. mypy is available as plugins in almost every Python IDE.
For more details of mypy availability. Check mypy’s Github !
If you are not looking for installing mypy, you can also try mypy in an online playground (developed by Yusuke Miyazaki).
mypy is a great tool to use. It can help you find dozens of bugs that can go undetected. In The Zen of Python, these were called silent killers. You can get rid of them and this tool will become more valuable as your code become bigger and bigger. Making this tool work will save you plenty of time in debugging your code and getting rid of the errors.
For feedback, contact me on Linkedin!