You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here is a simple pattern I'm thinking to use, to let a function indicate the Exceptions it may raised, which can be used:
by the developper as documentation,
by the static type checker for exhaustiveness
fromtypingimportNoReturn, cast, TypeAliasclassSomeError(Exception):
...
classAnotherError(Exception):
...
classStillAnotherError(Exception):
...
FooError: TypeAlias=ValueError|SomeError|AnotherErrordefassert_never(value: NoReturn) ->NoReturn:
# This also works at runtime as wellassertFalse, f"This code should never be reached, got: {value}"deffoo(i: int):
ifi==0:
raiseValueError("Must not be zero")
elifi==1:
raiseSomeError("Must not be one")
elifi==2:
raiseAnotherError("Must not be two")
print("that's ok")
try:
foo(0)
exceptExceptionase:
e=cast(FooError, e)
ifisinstance(e, ValueError):
print("value error")
elifisinstance(e, SomeError):
print("some error")
else:
assert_never(e)
raise
It's far from being perfect, but it's simple and not too much intrusive nor obscure.
In the above example, mypy can tell me which exception I forgot to manage:
foo.py:43: error: Argument 1 to "assert_never" has incompatible type "AnotherError"; expected "NoReturn" [arg-type]
Found 1 error in 1 file (checked 1 source file)
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
edit: I've rather asked on https://mail.python.org/archives/list/typing-sig@python.org/, it's waiting moderation.
Hi everyone,
I've read https://stackoverflow.com/questions/44282268/python-type-hinting-with-exceptions and especially the https://jonathan-scholbach.github.io/2023/02/06/what-does-it-mean-to-be-exceptional/ blog post, but I want to keep coding with exceptions rather than returning
Ok | Err
.Here is a simple pattern I'm thinking to use, to let a function indicate the
Exception
s it may raised, which can be used:It's far from being perfect, but it's simple and not too much intrusive nor obscure.
In the above example,
mypy
can tell me which exception I forgot to manage:What do you thing of this?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions