Documentation: Annotations
Learn how annotations are used for type hinting in Python.
We'll cover the following...
The basic idea of annotations is that they hint to the readers of the code what to expect as values of arguments in functions. The use of the word hint is not casual; annotations enable type hinting.
Annotations let us specify the expected type of some variables that have been defined. It is actually not only about the types, but any kind of metadata that can help us get a better idea of what that variable actually represents.
Consider this example:
from dataclasses import dataclass@dataclassclass Point:lat: floatlon: floatdef locate(latitude: float, longitude: float) -> Point:"""Find an object in the map by its coordinate"""
Here, we use float
to indicate the expected types of latitude and longitude. This is merely informative for the reader of the function so they can get an idea of these expected types. Python will not check these types nor enforce them.
We can also specify the expected type of the returned value of the function. In this case, Point
is a user-defined class, so it will mean that whatever is returned will be an instance of Point
.
However, types or built-ins are not the only kind of thing we can use as annotations. Basically, everything that is valid in the scope of the current Python interpreter could be placed there. For example, it could be a string explaining the intention of the variable, a callable to be used as a callback or validation function, and so on.
We can leverage annotations to make our code more expressive. Consider this next example of a function that is supposed to launch a task, but that also accepts a parameter to defer the execution:
def launch_task(delay_in_seconds):...
Here, the name of the argument delay_in_seconds
seems quite verbose, but despite ...