Python type hints
In this section, we will look at type hints. Type hints are a way to annotate your Python code with information about the expected types of variables, function arguments, and return values.
Python is dynamically typed, so this is not required. However, type hints help both humans and tools understand your code, which can catch bugs early and improve code readability and maintainability.
Type hints are part of the Python standard library since Python 3.5. For more details, see PEP484 which introduced type hints and thetypingmodule documentation. Importantly, type hints do not change the runtime behavior of your code; they are simply annotations.Why use type hints?
- Clarity: Type hints make it clear what types your functions expect and return.
- Early error detection: Tools like
mypycan check your code for type errors before you run it. - Better IDE support: Many editors use type hints for autocompletion and inline documentation.
Type hints use the
:syntax for variables and function arguments, and->for return types. For example:# Variable annotation a: int = 5 # Function annotation def add(x: int, y: int) -> int: return x + yExamples of common types you may use in Python 3.9 and later:
int,float,str,bool: Basic typeslist,dict,set,tuple: Collection types.
These can be combined using bracket notation like:
list[int],dict[str, float], etc.You can also import additional types from the
typingmodule or other modules you useType hints are not enforced at runtime, but you can use tools like
mypyto check your code for type errors. To check your typed code, run:mypy your_script.pymypywill report any type mismatches it finds, helping you catch bugs before they happen.If you want to learn more, check out: