python / python/mypy

no error when using generic in `except` block

Open
#17,248 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-runtime-semantics
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

from typing import Generic, TypeVar

T = TypeVar("T")


class Foo(Exception, Generic[T]): ...


try:
    raise Foo
except Foo[int]: # no error, crashes at runtime
    ...

playground

this should be a type error because it fails at runtime with the following exception:

TypeError: catching classes that do not inherit from BaseException is not allowed

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied Python reproducer with mypy and inspect how generic exception types are handled in an except clause. Trace the relevant type-checking path and add a regression test for this example; done means mypy reports a type error instead of accepting code that fails at runtime.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.