How to Use Type Annotations in Python

preview_player
Показать описание
Type annotations - also known as type signatures - are used to indicate the datatypes of variables and input/outputs of functions and methods.

In many languages, datatypes are explicitly stated. In these languages, if you don't declare your datatype - the code will not run.

Type annotations have a long and convoluted history with Python, going all the way back to the first release of Python 3 with the initial implementation of function annotations.

Type annotations in Python are not make-or-break like in other languages (like C). They're optional chunks of syntax that we can add to make our code more explicit.

Erroneous type annotations will do nothing more than highlight the incorrect annotation in our code editor - no errors are ever raised due to annotations.

So, if type annotations are not enforced, why use them?

Well, as we touched upon already - declaring types makes our code more explicit, and if done well, easier to read - both for ourselves and others.

🤖 70% Discount on the NLP With Transformers in Python course:

Read the Medium article here:

📖 Here's a free link:

🕹️ Free AI-Powered Code Refactoring with Sourcery:

00:00 Intro
00:55 Datatypes Example in C
2:53 Static and Dynamic Typed Languages
3:47 Type Annotations in Python
4:25 How to Define Simple Types
6:04 IDE Warnings
8:20 More Complex Types
9:53 dict[str, int]
11.07 Multiple Types
11:38 Union Operator (Py 3.9)
12:34 Union Operator (Py 3.10)
13:21 Optional Operator
Рекомендации по теме
Комментарии
Автор

cool vid. Do you happen to know why I keep getting "Invalid Syntax" whenever I try to annotate using the arrow "->" I am using Python 3.

MrMarcBrook
Автор

Excellent, I didn't understand why wasn't working for me, but you clarified, thanks bro

e-raticartist
Автор

Nice and clean. Very good explonation!

Pheshen
Автор

Why has w3schools not covered that yet

liri
Автор

Neat Explanation!👌, Are you on twitter!, Please share me your twitter id, would like to tag you with the blog in my personal sharing of the medium blog !😀

sukanya