Skip to content

Return types for (Base)ExceptionGroup.derive(), .subgroup(), and .split() should not use Self #9219

Closed
@Zac-HD

Description

@Zac-HD

In the following stubs, each use of Self in a return type is incorrect:

typeshed/stdlib/builtins.pyi

Lines 1947 to 1959 in c626137

@overload
def subgroup(
self, __condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...]
) -> BaseExceptionGroup[_BaseExceptionT] | None: ...
@overload
def subgroup(self: Self, __condition: Callable[[_BaseExceptionT_co], bool]) -> Self | None: ...
@overload
def split(
self: Self, __condition: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...]
) -> tuple[BaseExceptionGroup[_BaseExceptionT] | None, Self | None]: ...
@overload
def split(self: Self, __condition: Callable[[_BaseExceptionT_co], bool]) -> tuple[Self | None, Self | None]: ...
def derive(self: Self, __excs: Sequence[_BaseExceptionT_co]) -> Self: ...

This is because .derive() must be manually overridden to return custom subtypes, in which case the child class should also manually update the type annotations on .subgroup() and .split()1. For example:

class MyGroup(ExceptionGroup):
    pass

excs = [Exception("oops")]
mg = MyGroup("msg", excs)
assert type(mg.derive(excs)) == ExceptionGroup  # *not* the Self type!

Discovered via agronholm/exceptiongroup#40 (comment); if accepted here we should make sure to fix the backport too.

Footnotes

  1. since I don't know of a way to express "that other method's return-type" in an annotation

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions