Typing Module

Last Updated: 24th August 2025


The typing module provides a way to annotate the types of variables, arguments, and return values in your Python code.ython is dynamically typed (no need to declare types), but for big projects (like DS pipelines, ML models), adding type hints makes code more readable and maintainable.

List of Type Functions:

  • typing.Any: A type that can hold any value.
from typing import Any

# Example 1
def print_value(x: Any) -> None:
    print(x)

print_value(42)       # int
print_value("hello")  # str

# Example 2

def add(x: Any, y: Any) -> Any:
    return x + y
add(1, 2)  # 3
add("hello", "world")  # "helloworld"
  • typing.Optional: A type that can hold a value or None.
from typing import Optional

# Example 1
def print_value(x: Optional[int]) -> None:
    if x is not None:
        print(x)

print_value(42)       # int
print_value(None)     # None

# Example 2

def add(x: Optional[int], y: Optional[int]) -> Optional[int]:
    if x is not None and y is not None:
        return x + y
    return None
add(1, 2)  # 3
add(None, 2)  # None
add(1, None)  # None
add(None, None)  # None
  • typing.List: A type that represents a list of values. It can hold any type of value.
from typing import List

# Example 1
def print_list(x: List[int]) -> None:
    for item in x:
        print(item)

print_list([1, 2, 3])  # 1 2 3

# Example 2

def square_all(nums: List[int]) -> List[int]:
    return [x*x for x in nums]

print(square_all([1,2,3]))  # [1,4,9]
  • typing.Dict: A type that represents a dictionary of key-value pairs. It can hold any type of key and value.
from typing import Dict

# Example 1
def print_dict(x: Dict[str, int]) -> None:
    for key, value in x.items():
        print(f"{key}: {value}")

print_dict({"a": 1, "b": 2})  # a: 1 b: 2

# Example 2
def student_scores() -> Dict[str, float]:
    return {"Aman": 85.5, "Rahul": 92.0}
  • typing.Tuple: A type that represents a tuple of values. It can hold any type of value.
from typing import Tuple

# Example 1
def print_tuple(x: Tuple[int, str]) -> None:
    print(x)

print_tuple((1, "hello"))  # (1, 'hello')

# Example 2
def get_coordinates() -> Tuple[float, float]:
    return (12.3, 45.6)
  • typing.Set: A type that represents a set of unique values. It can hold any type of value.
from typing import Set

# Example 1
def print_set(x: Set[int]) -> None:
    for item in x:
        print(item)

print_set({1, 2, 3})  # 1 2 3

# Example 2
def unique_labels(labels: List[str]) -> Set[str]:
    return set(labels)

print(unique_labels(["spam", "ham", "spam"]))  # {'spam', 'ham'}
  • typing.Union: A type that represents a value that can be one of multiple types.
from typing import Union

# Example 1
def print_value(x: Union[int, str]) -> None:
    print(x)

print_value(42)       # int
print_value("hello")  # str

# Example 2
def to_str(x: Union[int, float]) -> str:
    return str(x)

print(to_str(42))  # '42'
print(to_str(3.14))  # '3.14'
  • typing.Sequence: A type that represents a sequence of values. It can hold any type of value.
from typing import Sequence

# Example 1
def print_sequence(x: Sequence[int]) -> None:
    for item in x:
        print(item)

print_sequence([1, 2, 3])  # 1 2 3

# Example 2
def total(values: Sequence[int]) -> int:
    return sum(values)

print(total([1,2,3]))   # list
print(total((4,5,6)))   # tuple
  • typing.Callable: A type that represents a callable object, such as a function or method.
from typing import Callable

def apply_operation(x: int, y: int, func: Callable[[int, int], int]) -> int:
    return func(x, y)

print(apply_operation(3, 4, lambda a,b: a+b))  # 7
  • typing.Generator: A type that represents a generator object, which is a function that returns an iterator.
from typing import Generator

def data_stream() -> Generator[int, None, None]:
    for i in range(5):
        yield i

for item in data_stream():
    print(item) # 0 1 2 3 4
  • typing.TypeVar: A type variable that can be used to create generic types.
from typing import TypeVar

T = TypeVar("T")

def identity(x: T) -> T:
    return x

print(identity(42))  # 42
print(identity("hello"))  # 'hello'