Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created March 12, 2026 04:33
Show Gist options
  • Select an option

  • Save mypy-play/23d692cb9e92b3b4b694050a19f4023b to your computer and use it in GitHub Desktop.

Select an option

Save mypy-play/23d692cb9e92b3b4b694050a19f4023b to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from typing import TypeVar, Generic
from collections.abc import Callable
BaseExcT_co = TypeVar("BaseExcT_co", bound=BaseException, covariant=True)
BaseExcT_co_default = TypeVar(
"BaseExcT_co_default", bound=BaseException, covariant=True, default=BaseException
)
class RaisesExc(Generic[BaseExcT_co_default]):
def __init__(
self,
expected_exception: (
type[BaseExcT_co_default] | tuple[type[BaseExcT_co_default], ...]
),
/,
*,
check: Callable[[BaseExcT_co_default], bool] | None = ...,
) -> None: ...
class RaisesGroup(Generic[BaseExcT_co]):
def __init__(
self,
expected_exception: RaisesExc[BaseExcT_co],
/,
*other_exceptions: RaisesExc[BaseExcT_co],
check: Callable[[BaseExceptionGroup[BaseExcT_co]], bool] | None = None,
) -> None: ...
def foo() -> None:
def check(exc: ValueError) -> bool:
return True
RaisesGroup(
RaisesExc(RuntimeError),
RaisesExc(ValueError, check=check), # error
)
RaisesGroup(
RaisesExc(RuntimeError),
_re := RaisesExc(ValueError, check=check), # no error
)
# no error
re = RaisesExc(ValueError, check=check)
RaisesGroup(
RaisesExc(RuntimeError),
re, # no error
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment