🏷️

Advanced Type Hints in Python

PythonAdvanced

Use advanced typing features.

Code Example

Python
from typing import TypeVar, Generic, Protocol, TypedDict

# Type variables
T = TypeVar('T')

def first_element(items: list[T]) -> T:
    return items[0]

print(first_element([1, 2, 3]))
print(first_element(["a", "b", "c"]))

# Generic classes
class Stack(Generic[T]):
    def __init__(self):
        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.push(1)
stack.push(2)
print(f"\nPopped: {stack.pop()}")

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

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

class Square:
    def draw(self):
        print("Drawing square")

def render(shape: Drawable):
    shape.draw()

render(Circle())
render(Square())

# TypedDict
class User(TypedDict):
    name: str
    age: int
    email: str

user: User = {
    "name": "Alice",
    "age": 30,
    "email": "alice@example.com"
}

print(f"\nUser: {user}")

# Literal types
from typing import Literal

def set_mode(mode: Literal["read", "write", "append"]) -> None:
    print(f"Mode set to: {mode}")

set_mode("read")
# set_mode("invalid")  # Type checker would catch this

# Union types
from typing import Union

def process(value: Union[int, str]) -> str:
    return str(value)

print(f"\nProcess int: {process(42)}")
print(f"Process str: {process('hello')}")

# Callable type
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)
print(f"\nApply result: {result}")

Explanation

TypeVar for generic functions. Generic[T] for generic classes. Protocol for structural typing. TypedDict for dict types. Literal for specific values.

Related Tutorials