How to Use Type Annotations in Python

jamescalam

James Briggs

Posted on April 27, 2021

How to Use Type Annotations in Python

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.

💖 💪 🙅 🚩
jamescalam
James Briggs

Posted on April 27, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related