Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. What are type hints?

Python · Functions & Decorators

What are type hints?

Mediumpython-17
typingtype-hintsmypyannotations

Question

What are type hints in Python?

Solution

Type hints (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.

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."

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext