#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
7 min read
•Question 34 of 41hard

Type Hints and Static Typing

Advanced type annotations in Python.

Type Hints

Basic Annotations

code.pyPython
def greet(name: str) -> str:
    return f"Hello, {name}"

def process_items(items: list[int]) -> dict[str, int]:
    return {"sum": sum(items), "count": len(items)}

Advanced Types

code.pyPython
from typing import (
    Optional, Union, Literal,
    TypeVar, Generic, Callable,
    Any, TypedDict, Protocol
)

# Optional (can be None)
def find_user(id: int) -> Optional[str]:
    return None

# Union of types
def process(data: Union[str, bytes]) -> str:
    return str(data)

# Python 3.10+ union syntax
def process(data: str | bytes) -> str:
    return str(data)

# Literal values
Mode = Literal["r", "w", "a"]
def open_file(path: str, mode: Mode) -> None:
    pass

Generics

code.pyPython
from typing import TypeVar, Generic

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self) -> None:
        self.items: list[T] = []

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

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

stack: Stack[int] = Stack()
stack.push(1)
stack.push(2)

Protocols (Structural Typing)

code.pyPython
from typing import Protocol

class Drawable(Protocol):
    def draw(self) -> None: ...

class Circle:
    def draw(self) -> None:
        print("Drawing circle")

def render(shape: Drawable) -> None:
    shape.draw()

render(Circle())  # OK, Circle has draw method

TypedDict

code.pyPython
from typing import TypedDict

class Person(TypedDict):
    name: str
    age: int
    email: str | None

person: Person = {
    "name": "Alice",
    "age": 30,
    "email": None
}

Callable Types

code.pyPython
from typing import Callable

def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
    return func(a, b)

result = apply(lambda x, y: x + y, 5, 3)