Introduction to Python Typing For Type Annotation

All programming languages can be classified under two main groups based on how and when we assign data-types to variables before the program runs. In this respect there can be static typed programming languages such as Java, C++ ,Go and dynamic typed programming languages such as Python, JavaScript, Julia.

However certain languages offers the freedom to either define the data type of a variable or not. By specifying the data type or annotating the data type for a variable during the definition of the variable, it offers certain benefits. Such as, catching missing functions, invalid type arguments or a mismatch between a data value and type of variable it’s assigned to before the program even has a chance to run the erroneous code and risk crashing.

Although Python is a dynamic typed programming languages we can still specify the data type of variables natively in newer version of python (ie 3.6 and upwards) or with the Typing module. Let us explore how to annotate the types for our variable.

By the end of this tutorial, you will learn

  • How to specify the types of variables
  • How to define and assign types for python functions
  • Different datatypes
  • etc

Let us start

Type Annotation in Python using the Typing module

The typing module comes as part of the standard library hence you will only need to import it when you are good to go.

The basic format for assigning types to a variable you are defining goes as below

name:str = "Jesse"
print(type(name))

In the above example the name is the variable, the value after the name variable :str is the datatype (strings) for the variable we are creating

# Explicitely specifying the datatype
name: str = "John Mark"
age: int = 24
salary: float = 1.4000
is_male: bool = True
b: bytes = b"thisbyte"

Checking types will result in the specified datatype. You can also use mypy – python library to help you check the types during type hinting.

print(type(age))
print(type(salary))
print(type(is_male))
print(type(b))

The results shows the type of data it is

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'bytes'>

When working with collections such as lists, tuples, sets and dictionary there are two main ways based on whether you are using Python 3.6 or Python 3.9 +.

from typing import List,Set,Tuple,Dict

places: List[str] = ['London', 'Accra', 'New Delhi']

The first item is the name of the variable followed by the datatype. Noticed that the datatype must start with capital letters in order not to be confused with the default python datatype respectively such as list, set,tuple or dict.

You can also define the datatype for each variable in our list/collections as below

places: List[str] = ["your string"]
even_numbers: List[int] = [2,4,6,8,10]

You can do the same for sets, tuples and dictionary as below

# For Sets
odd_num: Set[int] = {1,3,5,7}

# For Tuples
mytupl: Tuple[int] = (2,4,6)

You can also specify the size for tuples via

# Specify a tuple of fixed size
mytupl2: Tuple[int,str,float] =(3,"Hola",3.4)

For dictionaries you will have to specify the datatype for both the key and for the value.

mydict: Dict[key,value] = {'key':'value'}
# example
mydict: Dict[str,str] = {'name':'John James','gender':'Male'}

One more thing concerning lists datatype is that a list can have different datatype for each variable. In otherwords it can be heterogenous. In order to define the variables datatypes you can use the Union class with the List class from the typing module like below

from typing import Union
a1: List[Union[str,int,bool]] = ["hello",3,True]

In case you don’t know the datatype you can resort to the Any class or allow python to do it for you.

from typing import Union
# Any: if you don't know the type
a2: Any = "3hdjiorjdjds"

You can also assign types to functions and their arguments . For functions you may have to specify the datatype of the arguments as well as the expected return value using the -> followed by the datatype.

# Declaring types of functional arguments
def say_hello(name: str) -> str:
   """Say Hello"""
    res = 'Hello {}'.format(name)
    return res

You can also specify the type for multiple arguments as below

# For Multiple Functional Arguments
def add_numbers(num1: int,num2: int) -> int:
    return num1+ num2

Sometimes a function may take either a list or a tuple as an argument. In such a case you can use a Sequence.It is used when you don’t care if it is a list/tuple.

def square_it(elements: Sequence[float]) -> List[float]:
    return [a**2 for a in elements]

Let us ty out a function

# Parsing in a list of floats
>>> square_it([3.3,4.4,2.5])
[10.889999999999999, 19.360000000000003, 6.25]

# Parsing in a tuple of floats
>>>square_it((3.3,4.4,2.5))
[10.889999999999999, 19.360000000000003, 6.25]
Defining a New Datatype

You can also define a special new datatype of your choice.

Create A New Datatype
from typing import NewType,TypeVar
>>> EmployerID = NewType('EmployerID',int)
>>> type(EmployerID)
function

>>> def get_employer_name(employer_id: EmployerID)-> str:
   return str(employer_id)

>>> get_employer_name(EmployerID(230))
'230'

There are a lot of things we can do with the typing module . However we will end here.

You can also check out the video tutorial below. Learn more and increase your skill-set.

Thanks For Your Attention
Jesus Saves
By Jesse E.Agbe(JCharis)

Leave a Comment

Your email address will not be published. Required fields are marked *