Python Type Hints — Static Typing for Python

Python AdvancedType HintsFree Lesson

Advertisement

Python Type Hints — Static Typing for Python

Type hints document expected types and enable static analysis. They catch bugs before runtime and improve code readability.

Learning Objectives

  • Add type hints to functions and variables
  • Use advanced types (Union, Optional, TypeVar)
  • Define protocols and typed structures
  • Run mypy for static type checking

Basic Type Hints

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

def add(a: int, b: int) -> int:
    return a + b

# Variables
age: int = 25
name: str = "Alice"
scores: list[int] = [95, 87, 91]

Advanced Types

from typing import Union, Optional, TypeVar, Generic

# Union — multiple types
def process(value: Union[int, str]) -> str:
    return str(value)

# Optional — value or None
def find(name: str) -> Optional[dict]:
    return None

# TypeVar — generic types
T = TypeVar('T')

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

# TypedDict
from typing import TypedDict

class UserDict(TypedDict):
    name: str
    age: int
    email: str

# Callable
from typing import Callable

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

Protocol (Structural Subtyping)

from typing import Protocol

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

class Circle:
    def draw(self) -> str:
        return "O"

class Square:
    def draw(self) -> str:
        return "[]"

def render(shape: Drawable) -> str:
    return shape.draw()

render(Circle())  # "O"
render(Square())  # "[]"

Mypy Static Checking

# Install: pip install mypy
# Run: mypy your_script.py

def add(a: int, b: int) -> int:
    return a + b

add("hello", "world")  # mypy error: Argument 1 has type "str"

Key Takeaways

  1. Add type hints for better IDE support and documentation
  2. Use Optional[X] instead of Union[X, None]
  3. Use TypeVar for generic functions and classes
  4. Use Protocol for structural subtyping
  5. Run mypy to catch type errors statically

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement