100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Python Type Hints Cheat Sheet

Python Type Hints Cheat Sheet

Covers basic type annotation syntax, Optional and Union types, generics with TypeVar, and running static checks with mypy.

1 PageIntermediateMar 22, 2026

Basic Type Annotations

Annotate variables, parameters, and return values.

python
def greet(name: str) -> str:    return f"Hello, {name}"age: int = 30price: float = 9.99is_active: bool = Truenames: list[str] = ["Alice", "Bob"]        # Python 3.9+scores: dict[str, int] = {"Alice": 90}     # Python 3.9+point: tuple[int, int] = (1, 2)def add(a: int, b: int = 0) -> int:    return a + b

Optional, Union & None

Express values that may be absent or one of several types.

python
from typing import Optional, Uniondef find_user(user_id: int) -> Optional[str]:    return None  # equivalent to Union[str, None]def parse(value: Union[int, str]) -> int:    return int(value)# Python 3.10+ shorthanddef find_user_310(user_id: int) -> str | None:    return Nonedef parse_310(value: int | str) -> int:    return int(value)

Generics & Callable

Write reusable, type-safe containers and higher-order functions.

python
from typing import TypeVar, Generic, CallableT = 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()int_stack: Stack[int] = Stack()# Callable[[arg types], return type]def apply(fn: Callable[[int, int], int], a: int, b: int) -> int:    return fn(a, b)

Static Checking with mypy

Type hints do nothing at runtime — a checker enforces them.

bash
pip install mypymypy myapp.py                # Type-check a single filemypy myapp/                  # Type-check a packagemypy --strict myapp.py       # Enable all strict checks# type: ignore                # Inline comment to silence a specific line

typing Module Toolbox

Frequently used constructs beyond the basics.

  • Any- Opts a value out of type checking entirely; use sparingly
  • Literal['a', 'b']- Restricts a value to a fixed set of literal values
  • TypedDict- Defines a dict with a fixed set of typed string keys
  • Protocol- Defines structural typing (duck typing) instead of nominal inheritance
  • cast(Type, value)- Tells the type checker to treat value as Type; no runtime effect
  • @overload- Declares multiple type signatures for one function based on argument types
  • NewType- Creates a distinct type alias to prevent mixing similar primitive types
Pro Tip

Type hints are not enforced by Python at runtime — they're pure documentation until a tool like mypy or pyright checks them, so wire type checking into CI rather than trusting the hints alone.

Was this cheat sheet helpful?

Explore Topics

#PythonTypeHints#PythonTypeHintsCheatSheet#Programming#Intermediate#BasicTypeAnnotations#OptionalUnionNone#GenericsCallable#StaticCheckingWithMypy#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet