Python 3, an Illustrated Tour Transcripts
Chapter: Type Annotations
Lecture: Annotation syntax

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's just look at the basic syntax that was introduced in Pep 3107. Here we have a function foo and it's taking two parameters a and b
0:09 and following that we see a colon and then we see this expression here. So this here is the type annotation here,
0:17 note that b is a default variable, it has value 5 for the default value and in here we can put any expression, any Python expression in here
0:28 and we'll see some Python expressions. Note that there's also support for *args and **arguments.
0:34 So you can just put a colon following them and put an expression in there and there's also a way to specify the return value,
0:41 in order to specify the return value, this introduce this little arrow operator dash greater than -> and then we put the expression following that
0:49 and so if you have a function called sum and you want to indicate what it's returning you put that in this expression at the end,
0:56 note that it's coming before the colon there. One thing to note is that annotations are not supported in lambda functions,
1:02 so if you're a super fan of lambda functions and use those all over the place, you're not going to get the benefits of using annotations there
1:09 because you can't annotate them. 526 introduced the ability to annotate variables. And so this is how we annotate variables,
1:18 here we've got a name variable and we just put a colon and this expression in this case we're saying that this is str, a string
1:26 and note that this is the string class and that's a valid expression. One thing to note about this PEP is it introduced this construct down here,
1:35 which is a bare annotation on a variable with no assignment to it. So here I'm saying there is a variable called name2
1:42 and it will be a type string, but I'm not giving it a value. Note that if we simply said name2 by itself without the annotation
1:50 we would get a name error in Python. But in this case, it's going to create an annotation for that variable,
1:55 note that this variable also does not exist at this point in time. If we say name2 after it, we will get a name error.


Talk Python's Mastodon Michael Kennedy's Mastodon