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
In the except* block, eg is an ExceptionGroup instance that in its exceptions attribute contains either ValueError instances or more nested ExceptionGroups containing ValueErrors. I expect that many except* blocks will do operations specific to the exception type they operate on, but right now there's no way to represent that information in the type system.
To fix this, we can make ExceptionGroup (and BaseExceptionGroup) generic. In the example, eg would be of type ExceptionGroup[ValueError] (to static type checkers), indicating that all the contained exceptions are ValueErrors.
Recommendations:
In CPython, add the C equivalent of __class_getitem__ = GenericAlias to ExceptionGroup and BaseExceptionGroup.
In typeshed, make ExceptionGroup (and base) generic over a TypeVar("ExceptionT", bound=Exception), and type its exceptions attribute as tuple[ExceptionT | ExceptionGroup[ExceptionT], ...].
In type checkers, for code of the form except* T as eg:, infer eg to be of type ExceptionGroup[T]. (Or BaseExceptionGroup[T] if T does not inherit from Exception.)
If we're in agreement, I can implement the first two recommendations.
Thanks to PEP 654, 3.11 will have the new
except*
syntax. Let's take this sample:In the
except*
block,eg
is anExceptionGroup
instance that in itsexceptions
attribute contains eitherValueError
instances or more nestedExceptionGroup
s containingValueError
s. I expect that manyexcept*
blocks will do operations specific to the exception type they operate on, but right now there's no way to represent that information in the type system.To fix this, we can make
ExceptionGroup
(andBaseExceptionGroup
) generic. In the example,eg
would be of typeExceptionGroup[ValueError]
(to static type checkers), indicating that all the contained exceptions areValueError
s.Recommendations:
__class_getitem__ = GenericAlias
toExceptionGroup
andBaseExceptionGroup
.ExceptionGroup
(and base) generic over aTypeVar("ExceptionT", bound=Exception)
, and type itsexceptions
attribute astuple[ExceptionT | ExceptionGroup[ExceptionT], ...]
.except* T as eg:
, infereg
to be of typeExceptionGroup[T]
. (OrBaseExceptionGroup[T]
ifT
does not inherit fromException
.)If we're in agreement, I can implement the first two recommendations.
Links:
cc @iritkatriel @gvanrossum for PEP 654, @srittau @AlexWaygood for typeshed, @erictraut as a type checker maintainer.
The text was updated successfully, but these errors were encountered: