Creating and Modifying Annotations
Since it is a function attribute, you can access it using the dot operator. So if I define a function without any attributes, and then later I would like to add them, I can do it directly by creating the
Now, it’s supposed to be a dictionary and the dictionary is supposed to tell us what type, or any information we want about each of the parameters, and the return value. If we model this based on what we had in the last lesson,
a is supposed to be an
int to mean it’s an integer,
b was a
str (string), and for what it returns, that was supposed to be a
Here’s another interesting example, where you can actually write an annotation that can be modified during program execution. We’re going to create a new function, so this is a new function
f(), and we’re going to say that its return annotation is
And so when the
__annotations__ attribute is created, there’s going to be one entry in the dictionary. The keyword is going to be the string
'return', and the value is actually going to be the number
But each time we run this function, we’re going to get that value and increment it by
1. And so if we call the function, we get that the function has been executed one time. If I call the function again, that value in the annotations dictionary is incremented again, and now we get that this function has been executed twice.
And this will continue to increment every time we call it, and so
__annotations__ is keeping metadata about the function. In this particular case, it’s keeping track of how many times the function has been executed.
Become a Member to join the conversation.