Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ExceptionGroup should be generic #91549

Closed
JelleZijlstra opened this issue Apr 14, 2022 · 3 comments
Closed

ExceptionGroup should be generic #91549

JelleZijlstra opened this issue Apr 14, 2022 · 3 comments
Labels
3.11 only security fixes topic-typing

Comments

@JelleZijlstra
Copy link
Member

Thanks to PEP 654, 3.11 will have the new except* syntax. Let's take this sample:

try:
    do_failing_things()
except* ValueError as eg:
    reveal_type(eg)

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.

Links:

cc @iritkatriel @gvanrossum for PEP 654, @srittau @AlexWaygood for typeshed, @erictraut as a type checker maintainer.

@JelleZijlstra JelleZijlstra added 3.11 only security fixes topic-typing labels Apr 14, 2022
@iritkatriel
Copy link
Member

Is this related?

def test_exception_group_is_generic_type(self):

@iritkatriel
Copy link
Member

@JelleZijlstra
Copy link
Member Author

Great, you're well ahead of me :). I should have checked. Then we just need to make the corresponding typeshed change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3.11 only security fixes topic-typing
Projects
None yet
Development

No branches or pull requests

2 participants