Python is a dynamically typed language and type hints are not mandatory. Python interpreter automatically identifies object types during code execution and it also allows objects to dynamically change their types during the lifetime. However, optional type hints were introduced in Python 3.5, allowing programmers to use type hints if they wish.
Do note that unlike other programming languages, Python interpreter itself does not enforce optional type hints as it considers them as hints only. You will have to use third party modules or text editor plugins to enforce strict type checking in Python.
Why Use Type Hints?
Type hints explicitly state object types and they reduce code ambiguity. They make it much easier to infer logic behind code statements, especially when the same codebase is being worked upon by multiple members of a team. They are also useful when codebases are accessed after long intervals as type hints make it easier to infer underlying logic. Type hints can make it much easier to debug code when issues and crashes occur. However they do increase verbosity in code and some developers may not like it as it affects the standard Python syntax which is much cleaner. Usage of type hints in Python programs can also be a personal choice based on one’s coding style and patterns. As stated earlier, even when using type hints, the Python interpreter doesn’t enforce them and you may have to install a third party module to enable strict type checking.
Basic Syntax and Usage
The following example shows type hints used for an “int” type object in Python:
return number * number
print(square(5))
The first statement defines a function called “square”. It takes a mandatory argument called “number” and calculates its square. The type hint for number argument is defined as “int” using “:” (colon) symbol while the type hint for return type is again defined as “int” using a “->” (arrow) symbol.
Without type hints, the same function would be defined as follows:
return number * number
print(square(5))
You will get the following output after running the two code samples stated above:
25
If you just want to assign a type hint to a variable during its declaration, use the following syntax:
var2: int = 5
var3: float = 6.0
You can assign type hints to variables before “=” equal sign. As explained above, object names and type hints need to be separated by a “:” (colon) symbol.
Python interpreter doesn’t enforce type hints. So if you change the type of objects to any other random type available in Python, you will get the same result as long as the logic itself doesn’t throw an error. Here is code sample:
return number * number
result = square(5)
print(result)
print(type(result))
Here, the number argument is of “float” type. The function “square” now returns an “str” type object. However, both these types are not enforced and you will get “25” as output and the returned value will be of “int” type. After running the above code sample, you should get the following output:
<class 'int'>
Using Type Aliases
To define type hints for complex objects containing multiple types or custom object types, you can use type aliases. The following code sample shows usage of type aliases:
def square(numbers: IntegerList) -> IntegerList:
return [n * n for n in numbers]
result = square([5, 6, 7])
print(result)
In the first statement, a new type alias called “IntegerList” is defined by assigning it a type. The type definition can be simple or complex containing multiple types. Next, this type alias is then used in the square function and it is assigned to the main argument and return value. The square function now returns the square of each number in a list. After running the above code sample, you should get the following output:
Using “Any” Type Hint
The “Any” type can be used to annotate variables, arguments, and return types with any type hint. Objects with “Any” type hint can be a string, an integer, a float, or any other valid type in Python. Here is an example:
var1: Any = "string"
var2: Any = 5
var3: Any = 6.0
The first statement imports “Any” type from the “typing” module. The typing module provides support for type hints in Python programs and you have to import certain types from it in order to use them. Next, instead of using str, int, float or any other such type hint, “Any” is used to indicate that the variable can be of any type during its lifetime. Do note that type hints are still not enforced in Python without using any third party library.
Using a Third Party Module to Check Type Hints
Mypy is one of the most widely used type checking modules available for Python. You can use it to find type hint related errors in your Python programs. You can install it in Ubuntu and other Linux distributions from the pip package manager. To do so, run one of these commands:
$ pip3 install mypy
Once mypy has been installed in your Linux system, you can check strict type checking issues in a Python program by executing a command in the following format:
Note that mypy is just a tool to check strict checking. It will run a report on your Python program and show you type checking errors. However, you will still be able to run Python programs normally (with or without type hints) and no type hint related errors will be thrown during execution. Consider the following code sample:
return number * number
result = square(5)
print(result)
This code sample is identical to one of the examples explained above. Assuming that it resides in a “main.py” file, you can check type hints using mypy by running the following command:
After running the above command, you should get the following output:
If you supply a float type object to the square function call in the same example above, mypy will throw an error.
return number * number
result = square(5.0)
print(result)
Now when you run the file using “mypy main.py” command, you will get an error similar to this:
This is just an error report that will show you type hint errors. If you execute both code samples mentioned above without mypy, you will get the following output:
25.0
This covers the most basic and common usage of type hints syntax in Python. For further information on type hints, advanced usage and custom types, refer to official Python documentation available here.
Conclusion
Type hints in Python provide a systematic way to attach type indicators to variables, functions and classes. While Python itself doesn’t enforce type hints, you can use third party modules to check type hints and use them as a basic form of tests to assert intended behavior of Python objects in your program. The way Python programming language is designed and its core philosophy, strict type checking for type hints may never be implemented in the standard Python library.