Skip to the solution
MediumDSA12 min read

How do type hints work in Python?

41 views

The problem

Question presented to candidate: "Walk me through type hints in Python. If I annotate a parameter as int and pass a string, what happens? Then what are the hints actually for, and who reads them?"

What a strong answer should cover:

  • Hints are annotations: expressions attached to parameters, return values and variables; CPython stores them in __annotations__ and never enforces them at runtime
  • Static type checkers (mypy, pyright) read them without running the code and report mismatches; IDEs use them for completion; this is gradual typing, where unannotated code is treated as Any
  • Core vocabulary: list[int], dict[str, int], X | None (same as Optional[X]), Callable, Any, Literal, plus TypeVar for generics and Protocol for structural typing
  • When annotations are evaluated: eagerly at def time up to 3.13, as strings with from __future__ import annotations, lazily by default from 3.14 (PEP 649); typing.get_type_hints() resolves forward references
  • Some libraries do read hints at runtime: dataclasses builds fields from them, Pydantic and FastAPI validate data with them

Code / implementation expected: Optional β€” annotate a function, pass a wrong type to show nothing happens at runtime, then show what a checker reports or what __annotations__ holds.

  • typing

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonHints are stored, not enforced: __annotations__, forward references, evaluation time
PythonHint objects at runtime: unions, Annotated, dataclasses, a tiny checker, string annotations

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 117 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

How does Python manage memory and garbage collection?

Continue