Christopher Tyler

Using Assert Never in Python

This is from this article.

Assert Never in Python

This will work in Python 3.11:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
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:

1
2
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.

<< Previous Post

|

Next Post >>

#Assert_never #Error #Python