In this lesson, you will learn,
- what is type hinting
- the need for type checking.
Dynamically vs Statically Typed Languages
Python is a dynamically typed language. Dynamic means the variable type is not declared when assigning the variable. Instead, variable types are checked at runtime.
This is somewhat different from statically typed languages such as C, Java and Go, where the variable type is defined at the point of variable assignment.
Why does this matter? Well, let’s take an example. Let’s say in Python we set the variable
vlan_id, for which we assign a string value of
100. Along with this, we also create a function to perform an action to this variable, such as increment the value by 1:
vlan_id = "100" def add_vlan(vlan_id): return vlan_id + 1
However, if we now call our function, at runtime we will get an error as we are trying to add an integer (number) to a string. In other words, our variable
vlan_id should have been assigned an integer-based value instead of a string-based value.
>>> add_vlan(vlan_id) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in add_vlan TypeError: can only concatenate str (not "int") to str
So what can we do to prevent issues such as this? Well Python provides what is known as type hinting.
Type hinting allows us to hint (annotate) at what the value type should be.
Here’s an example where we are hinting that the
vlan_id should be an
int, both at the point of assignment and also when being supplied as the function input.
vlan_id: int = "100" def add_vlan(vlan_id: int): return vlan_id + 1
However, even though we have added type hints, we’ve only solved half the issue. Our type hints are only, well, a hint - an annotation on what the types “should” be. And, like before, the type checking will only occur at runtime. Therefore, in this case our code will still fail.
This is where we require a type checker such as mypy, which will parse these type hints and report any issues prior to runtime.