Why Are Annotations Useful?

In addition to comments written above or beside lines of code, as well as documentation strings (docstrings), Python also allows us to use annotations to help improve the understanding of source code. Annotations are essentially informative labels that can be applied at specific points in the code.

You can annotate function arguments and return values, as well as variables and object attributes. At these locations, annotations most often specify type names. This is especially useful because Python is a dynamically typed programming language, meaning that variables only take on a type after they are assigned a value—based on the type of that value. Because of this, just by looking at a function header, we cannot tell what types of arguments are expected, nor do we know the type of the return value. An annotation that specifies a type name is called a type hint.

Type hints not only make code easier to read and understand, but they also enable advanced code editors, development environments, and specialized tools (such as static type checkers) to perform various analyses. Based on type hints, these tools can offer services that make writing code easier and more semantically safe—for example, checking type consistency, providing intelligent code completion, and suggesting operations valid for a particular type.

While most annotations serve as type hints, technically an annotation can be any valid expression. It’s not widely known that annotations written in a function’s header are accessible at runtime and can be processed by the program itself. To do this, you can use the function’s special attribute __annotations__. This is a dictionary where the keys are the parameter names and the values are the evaluated results of the annotation expressions.

To demonstrate this, consider the following function. Here, in addition to comments and a docstring, you’ll see annotations for both parameters and the return value. For the second parameter, instead of a simple type hint, we used an annotation expression that produces a dictionary specifying the minimum and maximum acceptable values for the argument. Inside the function body, we use this information to perform validation.

Further details and examples about annotations and how to process them can be found in the e-book Python Knowledge Building Step by Step, specifically in the chapters “Additional information in the source code for its better understanding” and “Special method and data attributes”.

Interested in the e-book Python Knowledge Building Step by Step: From the Basics to Your First Desktop Application?