pytest-dev/pytest · error · TypeError

Expected {expected}, but got an exception instance: {type(ex

Error message

Expected {expected}, but got an exception instance: {type(exc).__name__}

What it means

Raised when an exception INSTANCE is passed where an exception TYPE was expected. raises/RaisesExc want the class, not a constructed instance.

Source

Thrown at src/_pytest/raises.py:453

                and exc_type in (BaseException, Any)
            ):
                if not issubclass(origin_exc, ExceptionGroup):
                    self.is_baseexception = True
                return cast(type[BaseExcT_1], origin_exc)
            else:
                raise ValueError(
                    f"Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` "
                    f"are accepted as generic types but got `{exc}`. "
                    f"As `raises` will catch all instances of the specified group regardless of the "
                    f"generic argument specific nested exceptions has to be checked "
                    f"with `RaisesGroup`."
                )
        # unclear if the Type/ValueError distinction is even helpful here
        msg = f"Expected {expected}, but got "
        if isinstance(exc, type):  # type: ignore[unreachable]
            raise ValueError(msg + f"{exc.__name__!r}")
        if isinstance(exc, BaseException):  # type: ignore[unreachable]
            raise TypeError(msg + f"an exception instance: {type(exc).__name__}")
        raise TypeError(msg + repr(type(exc).__name__))

    @property
    def fail_reason(self) -> str | None:
        """Set after a call to :meth:`matches` to give a human-readable reason for why the match failed.
        When used as a context manager the string will be printed as the reason for the
        test failing."""
        return self._fail_reason

    def _check_check(
        self: AbstractRaises[BaseExcT_1],
        exception: BaseExcT_1,
    ) -> bool:
        if self.check is None:
            return True

        if self.check(exception):
            return True

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Pass the exception class (ValueError), not an instance (ValueError()).
  2. If you intended to also match the message, pass the class plus match='oops'.
  3. If you have an instance variable, pass type(instance) instead of the instance.

Example fix

// before
pytest.raises(ValueError('oops'))
// after
pytest.raises(ValueError, match='oops')
Defensive patterns

Strategy: type-guard

Validate before calling

if isinstance(exc, BaseException):
    raise TypeError('pass the exception class, not an instance')
pytest.raises(exc)

Type guard

def is_exception_class(exc) -> TypeGuard[type[BaseException]]:
    return isinstance(exc, type) and issubclass(exc, BaseException)

Prevention

When it happens

Trigger: Calling pytest.raises(ValueError('oops')) or RaisesExc(ValueError()). Hits raises.py:453 when isinstance(exc, BaseException) is True (i.e. it is an instance, not a type).

Common situations: Developer constructs the exception to communicate the expected message, then passes the instance instead of the class; copy-paste from a raise statement.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/8a3ca6facf5608bd.json. Report an issue: GitHub.