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.
Activity
iritkatriel commentedon Apr 14, 2022
Is this related?
cpython/Lib/test/test_exception_group.py
Line 17 in c9d41bc
iritkatriel commentedon Apr 14, 2022
Yeah I think it's there: https://github.com/iritkatriel/cpython/blob/8912054607c3cc83da8517b2ee56c5b250d8a16c/Objects/exceptions.c#L1043
JelleZijlstra commentedon Apr 14, 2022
Great, you're well ahead of me :). I should have checked. Then we just need to make the corresponding typeshed change.