Skip to the solution
HardDSA11 min read

How does typing.Never enable exhaustive match checking?

895 views

The problem

Question presented to candidate: "typing.assert_never takes a parameter of type Never. What is Never, and why does annotating that one parameter let a type checker prove a match statement covers every case?"

What a strong answer should cover:

  • Never is the bottom type: the type with no values. A function returning Never never returns normally (it raises, exits or loops forever); a parameter of type Never can accept no argument.
  • Never was added in Python 3.11 (typing_extensions before); NoReturn is older and checkers treat the two as the same type. At runtime they are distinct special forms that cannot be instantiated or used with isinstance.
  • Narrowing: the checker subtracts each handled type from the subject's declared union; once everything is handled, the remaining type is Never and that branch is unreachable.
  • assert_never(arg: Never) -> Never turns "the leftover type is not Never" into an argument-type error that names exactly the unhandled type; when the match is exhaustive the call is fine (and mypy does not flag it as unreachable).
  • Because a call returning Never ends the path, code after it is unreachable and functions like fail() or sys.exit() satisfy any declared return type.

Code / implementation expected: Yes β€” a match over a union ending in case _: assert_never(x), and the checker output with and without the missing case.

  • typing
  • never
  • match

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

11 min read Β· 11 sections

Run the code

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

PythonNever at runtime, a toy narrowing model, and assert_never in a match
PythonNever as a return type and as a parameter type

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 122 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 TaskGroup handle cancellation and ExceptionGroup?

Continue