Type checking in Python in the right way

Original article was published by Bex T. on Artificial Intelligence on Medium

Understanding the Type System of Python

All programming languages fall into one of these two major Type Systems. Our beloved Python uses dynamic typing. In dynamically typed languages, variables are allowed to change their type as your script/program develops and the interpreter of the language does the type checking as the code runs.

In contrast to dynamic, there exists static typing. In programming languages such as C or Java, the checking is only performed when the code compiles.

Yes, dynamic languages offer more flexibility and more control over our code. But there are cases where programmers want some of their blocks of code to be static. If your project scope is small and only written for yourself, you often do not have to worry about type hinting.

However, if you write your script for others to read, or say you are developing a package to eventually upload it to PyPi, type hinting can hugely boost the readability of your code as well as make it less error-prone and easy to debug.

Let’s explore a use-case:

Ok, when I first saw it, that was the least Pythonic piece of code I have ever seen.

In the function header, str and bool after the colons specify the types of arguments that the function accepts. If the function receives objects other than strings, it either raises AttributeError or TypeError depending on the object. This is particularly useful because we often use packages written by other people and don’t see the function header directly before calling them.

Today’s modern IDEs, for instance, PyCharm has already a type checker built into which displays helpful warnings when you are typing:

Image created by the author

Using -> after closing brackets specifies the type of the result. Setting default values is also easy, just put the equal sign after the type annotation (that’s what they are called) and you are good to go.

If you have noticed, it is also possible to hint variable types as well. Though it is very rare, having the knowledge never hurts!