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

Add .subgroup() and .split() methods to BaseException #125825

Open
Zac-HD opened this issue Oct 22, 2024 · 0 comments
Open

Add .subgroup() and .split() methods to BaseException #125825

Zac-HD opened this issue Oct 22, 2024 · 0 comments

Comments

@Zac-HD
Copy link
Contributor

Zac-HD commented Oct 22, 2024

As we scale up our use of except* and ExceptionGroups, we've noticed that isinstance() checks get noticeably more clumsy:

# often the isinstance is implicit due to an except-statement
not_found = isinstance(err, HTTPError) and err.status_code == 404

# becomes

if isinstance(err, BaseExceptionGroup):
    # often we'd want .split() to do something with the other case, but for simplicity:
    not_found = err.subgroup(lambda e: isinstance(e, HTTPError) and e.status_code == 404) is not None
else:
    # as above

Obviously we use except T as err: or except* T ... wherever possible, but there are cases where we need to inspect metadata beyond the error type and duplicating the logic often gets messy.

By adding .subgroup() and .split() methods to BaseException, which for non-groups act as if the exception was wrapped in a single-member group, we can avoid duplication and write only the necessarily-more-complicated code for groups to cover both cases.

(opening issue as discussed with @gpshead and @njsmith elsewhere)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant