This is a feature of Python that begins with version 3, and it’s a way to attach metadata to your function’s parameters and return value. For a parameter, you create it by following the parameter name with a colon (
:) and then providing whatever annotation goes with it. For the return value, following the parameter list you use an arrow (
->) and then the annotation before the colon that ends the function header.
The annotation you create can be any valid expression or object within Python. That information is saved as a dictionary under the dunder attribute
__annotations__, which, like other function attributes, you can access using the dot operator.
Do the same thing for
b, and we’ll annotate that with another string—although these don’t have to be strings, this is just one example. And then following the parameter list, we can include an arrow to indicate an annotation for the return value, which in this case, is going to be another string, and then we follow that with a colon.
Remember, a dunder name begins and ends with a double underscore (
__). And we can see that we get a dictionary where the keys have been either the parameters as a string or the word
'return', and the values associated with each is the annotation we provided for each one.
We don’t have to use strings, and here are a couple of examples. I want to look at the first one right now. I can provide typing information. For example, I can say that
a should be an integer and that
b should be a string and that this function is going to return a floating-point value, which it does.
And likewise, if I want to look at the dictionary more closely, I can use the dot operator to get it. Notice now that our annotations describe that they represent objects of type class
str (string), and
03:54 Annotations can become even more complicated, where we can provide for each parameter, for example, a dictionary of its own, where we have, say, one key-value pair to indicate a description of what the parameter is and then another one to give us information about its type.
04:48 I can look at this. I can say, “What is the area of a circle?” Notice all of the useful information that I am told about the parameter that will allow me to use the function the way it’s supposed to be.
I get that the annotation for the radius is this dictionary. The annotation for
'return' is this dictionary. This allows me to learn lots of information and to pin down what I want to know. So, for example, if I want the description of what parameter
r is supposed to be, I can look it up. And if I want to know, let’s say, the type of the return value, I can look at the annotation for
'return', which itself is a dictionary.
Now, annotations aren’t enforced. Whatever’s put in an annotation isn’t enforced anywhere. So, we have this function
f() that’s expecting an integer and a string, but I can give it other parameter values
Become a Member to join the conversation.