Python Type Annotations

In Python, a type annotation or type hint is an optional notation that allows users to specify the type of parameters and return of a function.

Examples:

def add(a: int, b: int) -> int:
  '''Specify argument and return as int'''
  return a + b

def add_list(nums: list[int]) -> int:
  '''Specify argument as list of int and return as int'''
  sum = 0
  for num in nums:
    sum += num
  return sum

def make_dict(keys: list[str], values: list[int]) -> dict[str, int]:
  '''Specify arguments as lists of str and int,
  the return as a dict whose keys should all be str and value be int'''
  dict = {}
  for key, value in zip(keys, values):
    dict[key] = value
  return dict

Notice that adding type annotations to a function definition does not require the Python interpreter to check type arguments or return a converted value. The function will work as well with other type of input. Type annotations work more as function documentation, which helps increase the readability of the code.

Sometimes an argument is expected to work for different types, this can be done using Union class from the typing module

from typing import Union

def add(a: Union[float, int], b: Union[float, int]) -> Union[float, int]:
  '''Specify argument and return as int or float'''
  return a + b

For Python 3.10 and later, this can be achieved simply with the | operator

def add(a: float | int, b: float | int) -> float | int:
  '''Specify argument and return as int or float'''
  return a + b
  

typing includes various generic types and ability to customize type, which would be useful for complicated type relationships. Check a few examples .

A cheat sheet of various common types in Python can be found here.

NOTE

Third-party tools such as mypy can analyze code containing type annotations and flag potential problems.

Ref:




Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • DFT Calculations Using Quantum ESPRESSO
  • Longest Palindromic Substring
  • Negative Binomial Distribution