Grepping for assert_never in public code shows that people usually print the type of the object. https://grep.app/search?q=def%20assert_never%28&case=true&filter[lang][0]=Python

I propose `raise RuntimeError(f"Unexpectedly reached {type(arg).__name__}")`. I'm not sure I understand the vector for concern about untrusted input, but I believe printing the type should be fine; if you have an untrusted type in your program you have previous problems.

On Sun, 23 Jan 2022 at 15:42, Jelle Zijlstra <jelle.zijlstra@gmail.com> wrote:
I put up a draft implementation at https://github.com/python/cpython/pull/30842. Based on the feedback here, I am also proposing to add typing.Never as an alternative spelling for NoReturn.

El sáb, 22 ene 2022 a las 14:51, Jelle Zijlstra (<jelle.zijlstra@gmail.com>) escribió:
Another idea that came up in a few recent threads is a `typing.assert_never()` function, which indicates that some code is supposed to be unreachable. I will submit an implementation to CPython, and we can use this thread to work out any details (or to let me know that we shouldn't do this after all).

# Specification

We will add a new function `typing.assert_never()` with the following signature:

    def assert_never(arg: NoReturn, /) -> NoReturn: ...

At runtime, this will unconditionally raise `RuntimeError(f"Unexpectedly reached {arg!r}")` (wording suggestions welcome).

Type checkers should emit an error if the function is called with an argument that has a non-bottom type. Examples:

match bool():
    case True: pass
    case False: pass
    case _ as x: assert_never(x)  # ok

match int():
    case 0: pass
    case 1: pass
    case _ as x: assert_never(x)  # error: x is an int, not NoReturn

# Motivation

PEP 484 only allows NoReturn as a return type, but in practice all type checkers allow it in argument positions as a bottom type. Thus, a manually defined `assert_never()` function already has the behavior specified above. Adding the function to the standard library will make this behavior more discoverable for users.

Relatedly, I opened https://bugs.python.org/issue46475 to document NoReturn being a general bottom type.

# Open questions

Suggestions welcome for better wording in the runtime error.

There is a related proposal to rename NoReturn to Never. I'm lukewarm about that because renaming things always causes churn, but in any case let's discuss that separately.
_______________________________________________
Typing-sig mailing list -- typing-sig@python.org
To unsubscribe send an email to typing-sig-leave@python.org
https://mail.python.org/mailman3/lists/typing-sig.python.org/
Member address: hauntsaninja@gmail.com