Using Assert Never in Python

Using Assert Never in Python

April 1, 2025

This is from this article.

Assert Never in Python

This will work in Python 3.11:

from typing import assert_never, Literal

def calculate_commission(
    method: Literal['cash', 'credit_card', 'bank_transfer'],
    amount: int,
) -> float:
    if method == 'cash':
        return 100
    elif method == 'credit_card':
        return 30 + 0.02 * amount
    else:
        assert_never(method)

Running this code in Mypy will produce the following error:

error: Argument 1 to "assert_never" has incompatible type "Literal['bank_transfer']";
expected "NoReturn"

This will only generate an error during static analysis and won’t error during run-time.