Typing
Resources
- Typing documentation in the official Python documentation.
- Type checking guide in Real Python.
Typing
In Python, like in any other language, objects have types, like int, float, str or list. However, variables can hold objects of any type and they can change the type of object that they hold without any restriction.
In other languages, like C, Java or Rust the previous code would not even compile because a variable, once it has a type, it can’t change its type (or at least this is the general rule). Languages like Python in which variables and function arguments can change the type of objects they hold are called dynamic languages, and languages like C or Rust are called static.
Also, in Python function arguments can receive any type.
This can cause problems because you could cause an error by calling the function with incorrect types.
To avoid this kind of problems Python has added types, so now you can inform the user of the function about the expected types.
Now, thanks to the typing information the caller of the function knows which types are expected. Typing is optional, so you don’t need to annotate variables and function arguments with typing information and most Python code is not typed. In fact typing in Python has been introduced more as documentation than anything else, Python is still a dynamic language. Moreover, Python does not enforce this typing at runtime, so the caller would still be able to call the functions with incorrect types.
If you want to enforce the use of types in your code you could take a look at mypy, ty or pyrefly.