You can use something like https://github.com/dry-python/returns#result-container It just works right now! вс, 12 мар. 2023 г. в 21:40, <david.froger@mailoo.org>:
The first version can be simplified with a tuple of exceptions rather than a union:
``` from typing import NoReturn
class SomeError(Exception): ...
class AnotherError(Exception): ...
class StillAnotherError(Exception): ...
def assert_never(value: NoReturn) -> NoReturn: # This also works at runtime as well assert False, f"This code should never be reached, got: {value}"
FooError = (ValueError, SomeError, AnotherError)
def foo(i: int): if i == 0: raise ValueError("Must not be zero") elif i == 1: raise SomeError("Must not be one") elif i == 2: raise AnotherError("Must not be two") print("that's ok")
try: foo(0) except FooError as e: if isinstance(e, ValueError): print("value error") elif isinstance(e, SomeError): print("some error") else: # mypy successfully check for exhaustiveness: Argument 1 to "assert_never" has incompatible type "AnotherError"; expected "NoReturn" [arg-type] assert_never(e) raise ``` _______________________________________________ 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: n.a.sobolev@gmail.com