Python Typing Library – Using Type Annotations

In this tutorial, we will discuss the Typing Library which was introduced in Python 3.5 It’s a rather special library that builds on the concept of Type Hinting and Checking, and brings in some additional functionality.

If you are not aware of what Type Hinting is in Python, then it was best for you to check out our tutorial on Type Checking in Python first. Either way we will quickly go through the basics of Type hinting before proceeding.


What is Type Hinting/Checking?

In Statically-typed languages like C++ and Java, upon declaration of any variable or function parameter, it is given a type. However, in Python, which is dynamically-typed, no such concept exists.

var = 5
var = "Hello"   # Reassignment to a different type is legal

Hence these commands in python are perfectly legal. But this can cause confusion, and can make debugging harder. So we want to bring in the concept of Static Type checking in Python, which we will do with Type Hinting and one other thing (that we’ll mention later).

The following format is used to indicate that the variable var is only meant to hold integer values.

var: int = 5

Variable name, followed by a colon, then the type of the variable, followed an optional assignment operator and value. This is the format for using type hinting on variables.

Let’s take a look at another small example, where we create a function for adding only integers, and only returning integers. Anything that goes against this, will raise an error.

def add(one: int, two: int) -> int:
    return (one + two)

The arrow sign + type format that you see in the above example, is used to define the return type. If you trying calling this function with two strings, it will raise an error.

print(add("Hello", "World"))   # INVALID
print(add(5, 10))              # VALID

Note: In order for type hinting to actually raise errors, you need to have a static type checker. This may already be present inside an IDE you are using, but if not, then you need to setup a static type checker like mypy.

It may not seem like it at first glance, but there are actually many advantages of using type hinting, that make it worth putting in the extra effort.


Introducing the Typing Library

As we mentioned earlier, the Python Typing library builds upon the concept of Type Hinting, and gives us even more features and ways to define the type of objects we are using.

Previously, we could only declare the type of variables and functions. But now, with the Typing library, we can even define the type of Lists, Dictionaries, Tuples and other Python objects.

Let’s take a look at some short examples.

from typing import List, Tuple, Dict

# List of Strings
a: List[str]  

# Dict with strings as keys, and integers as values   
b: Dict[str, int]

# Tuple of ints
c: Tuple[int]

Attempting something like this…

a: List[str] = ["1", "2"]
a.append(3)

gives us the following error, as it only accepts string values.

PS D:\VSCode_Programs\Python> python -m mypy typehinting.py
typehinting.py:8: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
Found 1 error in 1 file (checked 1 source file)

With Tuples you can even define how many values it can hold.

# Valid
a: Tuple[str, str] = ("hi", "hello")  

# Invalid            
a: Tuple[str, str] = ("hi", "hello", "world")

The above Tuple has been defined as a Tuple which holds two strings. Attempting to store more than that will result in an error.


Combining together Types with Union

Another interesting tool that the typing library gives us, is Union. Union is a special keyword, which allows us to specify multiple allowed datatypes. If for example, we wanted a string that allows both integers and strings, how would we do so?

This is where Union helps, as shown in the below example.

from typing import List, Dict, Tuple, Union

mylist: List[Union[int, str]] = ["a", 1, "b", 2]

The above command is perfectly valid, as both int and str are allowed in mylist.

We can use Union anywhere, even with variables or in functions as the return type.

from typing import List, Dict, Tuple, Union

# myVar accepts both integers and strings
myVar: Union[int, str] 

myVar = 5
myVar = "Hello"

Other Keywords in the Typing Library

The Typing Library in Python is vast, and has extensive documentation. For a complete list of keywords, you can refer to it. Here we have covered all of the important ones, that we felt might come in handy.

Here are two more keywords, that might come in handy.

The Any type

As the name implies, this is used to define a variable that accepts “any” type.

from typing import Any

var: Any

var = 5
var = "Hello"
var = 1.23

All of the above 3 assignments, are all perfectly valid.

The NoReturn keyword

This keyword is used to indicate that a function is not returning anything. Below is a short code snippet using this keyword.

from typing import NoReturn

def display(x:int) -> NoReturn:
    print(x + 1)

The above function simply prints out a number after incrementing it, and doesn’t need to return anything. Hence we defined it as such.


This marks the end of the Python Typing Library Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments