Python __annotations__ Attribute

Rate this post

Annotations are defined in PEP 3107 allow you to add arbitrary metadata to the parameters and return values of functions. The __annotations__ attribute of a function object stores those annotations in a dictionary mapping function parameters or the return value to the specified annotations.

Let’s have a look at a couple of examples next.

Parameter Annotations

The syntax of a parameter annotation works as follows. You add a colon after the parameter name and add an arbitrary object or reference to an object after the colon. The parameter is now annotated with the object.

def f(param_1: annotation_1,
      param_2: annotation_2, ...):
    pass

The following code snippet shows a minimal example where you add string annotations to the input parameters of a given function. The function calculates the potential savings you’d obtain by investing x units of money at y annualized return for n years.

def save(x: "starting capital",
         y: "annual return (e.g., 0.1 == 10%)",
         n: "number of years"):
    return x * (1+y)**n

# Investing $10,000 at 10% for 50 years
print(save(10000, 0.1, 50))
# 1173908.5287969578
# = $1.1 million USD

You can print the annotations using the __annotations__ attribute of the function save:

print(save.__annotations__)
# {'x': 'starting capital', 'y': 'annual return (e.g., 0.1 == 10%)', 'n': 'number of years'}

Return Value Annotations

The syntax of a return value annotation works as follows. After the closing parenthesis of the definition of the function parameters, you add the -> arrow symbol, followed by the object or reference to an object associated with the return value of a function or callable.

def f(...) -> annotation:
    pass

You can add an annotation to the return value of the function as shown in the following example:

def save(x, y, n) -> "final capital":
    return x * (1+y)**n


print(save.__annotations__)
# {'return': 'final capital'}

The __annotations__ attribute stores a dictionary of key,value mappings where

  • the keys are the parameter names or the 'return' string in case of a return value annotation, and
  • the values are the annotation objects.