Python is a dynamically typed language, and hence the type of a variable is evaluated at runtime by the interpreter once a value has been assigned to the variable, as shown in the following code:
a = 10
type(a) # type(a) => 'int'
a = "Joe"
type(a) # type(a) => 'str'
Though dynamic interpretation of the type of a variable can be handy while writing small programs where the code base can be easily tracked, the feature of the language can also become a big problem when working with very large code bases, which spawn a lot of modules, and where keeping track of the type of a particular variable can become a challenge and silly mistakes related to the use of incompatible types can happen easily. Look at the following code:
def get_name_string(name):
return name['first_name'] + name['last_name']
username = "Joe Cruze"
print(get_name_string(username))
Let's see what happens if we try to execute the preceding program:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in get_name_string
TypeError: string indices must be integers
The program exited with a TypeError because we passed a string type to the get_name_string() method and then tried to access the keys inside a string, which is not the correct solution.
With the release of Python 3.5, the community added support for type hinting that was built into the language. This was not an effort to enforce a method, but was rather provided to support the users who may want to use modules that can catch errors that are related to a variable changing its type in between the execution flow.
The general syntax to mark the type of a variable is as follows:
<variable>: <type> = <value>
To mark the types in a method, the following syntax can be used:
def method_name(parameter: type) -> return_type:
# method body
One of the examples of how to use type hinting in the program code is shown in the following code:
from typing import Dict
def get_name_string(name: Dict[str, str]) -> str:
return name['first_name'] + name['last_name']
username = "Joe Cruze"
print(get_name_string(username))
When the preceding code is written in an IDE, the IDE can use these type hints to mark the possible violations of the type change of variable in the code base, which can prove out to be really handy by helping to avoid errors that are related to an incorrect type change when dealing with large code bases.
An important point that needs to be reiterated here is that using type hinting does not guarantee that the interpreter will raise an error if you pass a parameter with an incorrect type to the method. The type hinting support is not enforceable and should only be used either with other tools that can help check type violations or with IDEs to support the development process.