Skip to content

typing Module Complexity

The typing module provides support for type hints, allowing developers to annotate function parameters and return types for better code documentation and static analysis.

Complexity Reference

Operation Time Space Notes
Type annotation O(1) O(1) Define hint (no runtime check)
get_type_hints() O(k) O(k) k = number of annotations; involves string evaluation
Generic type creation O(1) O(1) Create parameterized type

Basic Type Hints

Function Annotations

from typing import Optional, List

# Type hints - O(1) (no runtime overhead)
def greet(name: str) -> str:
    return f"Hello, {name}"

# Optional type - O(1)
def find_user(user_id: int) -> Optional[str]:
    # May return str or None
    if user_id == 1:
        return "Alice"
    return None

# List type - O(1)
def sum_numbers(nums: List[int]) -> int:
    return sum(nums)

# Hints are just annotations, no enforcement
greet(123)  # Works! (type checker would complain)

Common Types

from typing import Dict, Tuple, Set, Union

# Dict - key and value types - O(1)
def process_config(config: Dict[str, int]) -> None:
    pass

# Tuple - element types - O(1)
def get_coordinates() -> Tuple[float, float]:
    return (0.0, 1.0)

# Set - element type - O(1)
def get_unique_ids(data: List[str]) -> Set[str]:
    return set(data)

# Union - multiple possible types - O(1)
def parse_input(value: Union[str, int]) -> str:
    return str(value)

Generic Types

Generic Functions

from typing import TypeVar, Generic

# TypeVar - represents any type - O(1)
T = TypeVar('T')

# Generic function - O(1)
def first(items: List[T]) -> T:
    return items[0]

# Usage - preserves type
numbers = [1, 2, 3]
first_num: int = first(numbers)  # Typed as int

strings = ["a", "b"]
first_str: str = first(strings)  # Typed as str

Generic Classes

from typing import Generic, TypeVar

# Type variable - O(1)
T = TypeVar('T')

# Generic class - O(1)
class Stack(Generic[T]):
    def __init__(self):
        self.items: List[T] = []

    def push(self, item: T) -> None:  # O(1)
        self.items.append(item)

    def pop(self) -> T:  # O(1)
        return self.items.pop()

# Usage
int_stack: Stack[int] = Stack()
int_stack.push(1)
int_stack.push(2)

Callable Types

Function Types

from typing import Callable

# Callable type - O(1)
def apply_operation(a: int, b: int, op: Callable[[int, int], int]) -> int:
    return op(a, b)

# Pass functions - O(1)
def add(x: int, y: int) -> int:
    return x + y

result = apply_operation(5, 3, add)  # 8

Higher-Order Functions

from typing import Callable, List

# Return function - O(1)
def create_multiplier(factor: int) -> Callable[[int], int]:
    def multiply(x: int) -> int:
        return x * factor
    return multiply

# Usage
times_three = create_multiplier(3)  # O(1)
result = times_three(5)  # 15

Union and Optional

Union Types

from typing import Union

# Union - multiple types - O(1)
def process_value(value: Union[int, str, float]) -> None:
    if isinstance(value, int):
        print(f"Integer: {value}")
    elif isinstance(value, str):
        print(f"String: {value}")
    else:
        print(f"Float: {value}")

# Works with any of the types
process_value(42)      # Integer
process_value