Python · Functions & Decorators

What are type hints?

Mediumtypingtype-hintsmypyannotations

Interview question

What are type hints in Python?

How to answer

The short answer

(PEP 484+) are optional annotations that declare expected types for parameters, returns, and variables. Python does not enforce them at runtime by default; tools like mypy, pyright, and IDEs use them for static checking and better autocomplete.

Python
from typing import Iterable, Optional

def normalize_name(name: str) -> str:
    return name.strip().title()

def find_user(user_id: int) -> Optional[dict[str, str]]:
    if user_id <= 0:
        return None
    return {"id": str(user_id), "name": "Asha"}

def mean(nums: Iterable[float]) -> float:
    values = list(nums)
    return sum(values) / len(values)

# Python 3.10+ union syntax
def parse(flag: str | None) -> bool:
    return bool(flag)

Benefits

  • Catch mismatches before production.
  • Document APIs without long prose.
  • Enable safer refactors.

Limits

  • Not a substitute for tests or runtime validation (use pydantic / explicit checks when needed).
  • Dynamic patterns may need Protocol, TypeVar, or Any carefully.

Interview line: "Type hints are for humans and static analyzers; CPython ignores them unless you opt into runtime use."

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill