Skip to content

Too tight a type constraint on ExceptionInfo.errisinstance #12667

@gmc444-b

Description

@gmc444-b
  • a detailed description of the bug or problem you are having
  • output of pip list from the virtual environment you are using
  • pytest and operating system versions (pytest versions; error should be OS-independent)
  • minimal example if possible

With pytest 8.2.2 the declaration of ExceptionInfo.errisinstance was

     def errisinstance(
        self, exc: Union[Type[BaseException], Tuple[Type[BaseException], ...]]
    ) -> bool:

With 8.3.1, this has changed, first by introducing a type spec, and then using that typespec for the function signature

EXCEPTION_OR_MORE = Union[Type[Exception], Tuple[Type[Exception], ...]]
    ...
    def errisinstance(self, exc: EXCEPTION_OR_MORE) -> bool:

Version 8.2.2 would pass a mypy check with the following reproducer. Version 8.3.1 fails (I didn't test with 8.3.0 but I'd expect that to also fail). I tested this with mypy versions 1.10.1 and 1.11.0, but I'd expect it to fail for pretty much any supported version of mypy.

import sys
import pytest


def test_iserrinstance() -> None:
    def bad() -> None:
        sys.exit()

    with pytest.raises(BaseException) as exc:
        bad()
    assert exc.errisinstance(SystemExit)

# Error output:
python3.10 -m mypy reproducer.py
reproducer.py:12: error: "ExceptionInfo[BaseException]" has no attribute "iserrinstance"; maybe "errisinstance"?  [attr-defined]
Found 1 error in 1 file (checked 1 source file)

The change was made in this commit but I'm not finding an explanation there as to why the type was changed from BaseException to Exception.

To me, it looks like the best fix is to change EXCEPTION_OR_MORE to

EXCEPTION_OR_MORE = Union[Type[BaseException], Tuple[Type[BaseException], ...]]

restoring backward compatibility.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: typingtype-annotation issuetype: regressionindicates a problem that was introduced in a release which was working previously

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions