Python / Core Python Fundamentals Interview Questions
How do Python type hints work and how do you use them in function signatures?
Type hints (PEP 484, Python 3.5+) let you annotate variables, function parameters, and return values with expected types. They are completely ignored at runtime by the interpreter but can be checked statically by tools like mypy, pyright, and IDE analysers, catching type errors before code ever runs.
def calculate_discount(price: float, pct: float) -> float: """Return the discounted price.""" return price * (1 - pct / 100) # Variable annotations name: str = 'Alice' items: list[int] = [] # Optional â value may be the type or None from typing import Optional def find_user(uid: int) -> Optional[dict]: ... # returns dict or None # Union type (Python 3.10+ shorthand: str | int) from typing import Union def parse(value: Union[str, int]) -> str: return str(value) # Python 3.10+ shorthand def parse310(value: str | int) -> str: return str(value) # List, Dict, Tuple from typing (3.9+ can use built-ins directly) from typing import List, Dict, Tuple def process(records: List[Dict[str, int]]) -> Tuple[int, int]: ...
From Python 3.9, you can use built-in collection types directly in annotations: list[int], dict[str, float], tuple[int, str] — no import from typing needed. From 3.10, X | Y replaces Union[X, Y]. Running mypy --strict script.py treats all un-annotated parameters as errors, giving you full type safety.
More Related questions...