Python Annotations

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

To talk in simple terms, python annotations make your code more documented. It makes the code easy for others to understand and enhances clarity. Annotations are mainly used to mention what data type a variable should hold and what data type a function should return. They do not enforce anything, the code works in the same manner as always.

  • PEP: PEP is the short-hand for the Python Enhancement Proposal. This is a design document that describes new features of Python or its processes or environments. It also provides information for the Python community. PEPs are the primary mechanism for proposing significant new features. For example, the Python Web Server Gateway Interface collects community contributions on issues and documents design decisions implemented in Python.
  • Python Functional Annotations: PEP 3107 introduced concepts and syntax for adding arbitrary metadata annotations to Python. This was introduced in Python3 where previously it was done in external libraries in Python 2.x.
  • Python Type Annotations: PEP 484 introduced type hints, also known as type annotations. Although the focus was on function annotations, but it introduced the concept of type comments for annotating variables. Type hints can be used in Python 3.6 and above.

Python Function Annotations

What are Python Function Annotations?

Python Function Annotations are the expressions written in a function in Python to make the function properly documented. Most function annotations include the data types of function parameters and the return type of the function. These are evaluated during compilation and do not interfere with the run time environment of Python.

Purpose of Python Function Annotations

Annotations can be read mostly by third-party libraries like mypy (A static code analysis tool), and linters. Let’s take a look at what purposes are served by Python Function Annotations:

  • We can mention the data types of the parameters and the return type of the function using python function annotations like:
    Even though annotations do not enforce variable a to be of integer type or variable b to be of float type, but a static code analysis tool, like mypy, will give us a warning in case we pass a string instead of an integer. That way it allows us to avoid such mistakes, making our coding experience much smoother!
  • The python annotations also help autocomplete extensions understand our intent and therefore we get suggestions for better codes!
  • String-based annotations can be used in libraries to improve compile-time help messages about the functionality of various methods, classes, and modules.

Syntax of Python Function Annotations

The syntax for using Function Annotations in Python is very simple. All you need to do is put a : after the variable and then write some expression after it, this can be, for example, the data type. Here are a couple of samples:

For Simple Parameters

For return types we use this -> symbol.

For nested parameters:

How to Access Python Function Annotations?

  • For accessing a function annotation in Python we use <functionName>.__annotations__ This returns a dictionary as we can see below.

    Code:

Output:

  • We can use the inspect library’s getfullargspec() function.

    Code:

    Output:

Applications of Python Function Annotation

Using with mypy

First, we need to install mypy using

Then let us run the following code and save it as mypySample.py

Run in the terminal using the: mypy mypySample.py

an error will be thrown as follow:

You can also use the mypy Playground to play around with annotations.

Using Python Function Annotations with Decorators

This code will generate an error since we are using decorators, so it’s not actually a String that’s being passed to the wrapper function, rather, it’s a function being passed. So an error is thrown by mypy.

Python Type Annotations

So, let’s get started with this kind of Python annotations.

What are Python Type Annotations?

This is something very similar to Python function annotations. Function annotations are used to tell the data type of parameters.

Python Type annotations are used to specify the data types of any variable.

You must be aware of languages where you need to specify the data type implicitly and those variables need to stick to them strictly. Can you name some of them??

Yes, JAVA, C++, C, and many more are there, these are all static in terms of data type. In all these languages we need to specify the data type of any variable, and the return type of any function.

But python dynamic and hence is forgiving, so we don’t do that here! But for having a better-documented code, Type annotations are used. Anyone who sees the code can now know what data type it is meant to store.

Let’s what static and dynamic mean in terms of data type.

Static Type vs Dynamic Type Languages

Static type languages are the ones where, if we mention a data type we need to strictly stick to it. Like in JAVA, C++, and C.

For example, in JAVA we cannot do:

Or,

These will throw errors.

Dynamic type languages are the ones where we do not need to mention the data type, like in Python. For example, in Python we can do:

Or,

None of the above will throw an error.

Application of Python Type Annotation

The application of using type annotation is similar to that of function annotations. If we run our programming using mypy then anything that’s not aligned with the annotations will be rendered as an error.

Let’s take some examples.

Example 1 (For simple data type):

Output:

Variable a is perfect. For variable b this happens because b is supposed to have a string as per the annotations but we are assigning an integer.

Example 2 (For complex data types): We can use annotations with lists and dictionaries as well. Let’s take the example for list

Output on mypy will be:

This happened because the function was expecting a list of int types but we sent a list of str types.

FAQs

Q: Is it Necessary to Put the Data Type Inside ‘’?

A: Absolutely NOT, we can do it either way.

Q: Can we consider functional annotation an extended version of type annotation?

A: Yes, that’s very true. Exceptionally, in functional annotation, we are defining the data types of parameters and the return data type of functions!

Q: Are comments and annotations the same thing?

A: NO! The comments cannot be read by the compiler, they are just there to make a person understand some logic in the code. Whereas, annotations can be understood by the Python online compiler thus helping us in many aspects like solving data type conflicts and better suggestions in autocomplete.

Conclusion

Let’s take a quick summary of Python Annotations

  • There are two types of Python annotations:
    • Python Function Annotations
    • Python Type Annotations
  • Python Annotations do not interfere with the code logic, this just makes our code more documented so that someone seeing the code finds it easy to understand what data type the variables are meant to hold and what data type the function is meant to return.
  • Python Annotations came into the picture in Python because Python is a dynamically typed language, unlike JAVA, C++, or C we do not need to specify the data types of variables
  • In functional annotation, we specify the data types of the parameters and the return type of the function.
  • In Python Type Annotation, we specify the data types of any variable in the code.
  • Python Function Annotation is an extended version of Python Type Annotation.

Read More: