type hint
In Python, a type hint is a syntactic construct that allows you to indicate the expected data types of variables, function arguments, and return values. They provide a way to improve your code’s maintainability by explicitly declaring the data type of variables, arguments, and return values.
Python doesn’t enforce type hints at runtime, but static type checkers, like mypy, can use them to detect potential type errors in your code before you run it.
Using type hints, you also create self-documented code, making it more clear for you and others to understand how to use functions and classes correctly.
Example
Here’s an example of using type hints in a Python function:
calculations.py
from typing import Union
Number = Union[float, int]
def add(a: Number, b: Number) -> float:
return float(a + b)
print(add(2, 4)) # Output: 6
print(add("2", "4")) # Output: '24'
In this example, the add()
function takes arguments that should be Number
objects, which are a type alias representing a union of the float
and int
types. The function should return a float
value.
If you run the script, you’ll note that the second call to add()
generates a results that isn’t a floating-point number. Python doesn’t catch this issue, but mypy does:
mypy calculations.py
calculations.py:10: error: Argument 1 to "add" has incompatible type "str";
expected "float | int" [arg-type]
calculations.py:10: error: Argument 2 to "add" has incompatible type "str";
expected "float | int" [arg-type]
Found 2 errors in 1 file (checked 1 source file)
The static type checker runs a type analysis on your code. As a result, you learn that your code has two errors on line 10. Those errors warn you about type inconsistencies in your code. With this information, you can go to your code and fix the inconsistencies so that the code works as expected.
Related Resources
Tutorial
Python Type Checking (Guide)
In this guide, you'll look at Python type checking. Traditionally, types have been handled by the Python interpreter in a flexible but implicit way. Recent versions of Python allow you to specify explicit type hints that can be used by different tools to help you develop your code more efficiently.
For additional information on related topics, take a look at the following resources:
- Python Protocols: Leveraging Structural Subtyping (Tutorial)
- Python Type Checking (Course)
- Python Type Checking (Quiz)
- Python Protocols: Leveraging Structural Subtyping (Quiz)
By Leodanis Pozo Ramos • Updated April 28, 2025