python / python/mypy

Incompatible type "Type[ImportError]"; expected "Type[Exception]"

Open
#14,443 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

Mypy appears not to consider ImportError to be an exception type in some cases.

To Reproduce

y = [
    # ValueError,
    ImportError,  # error: List item 0 has incompatible type "Type[ImportError]"; expected "Type[Exception]"  [list-item]
    AttributeError,
]
reveal_type(y)  # note: Revealed type is "builtins.list[def (*args: builtins.object, *, name: Union[builtins.str, None] =, obj: Union[builtins.str, None] =) -> builtins.Exception]"

The ordering of the list elements doesn't seem to impact the behaviour.

If you un-comment the ValueError however:

y = [
    ValueError,
    ImportError,
    AttributeError,
]
reveal_type(y)  # note: Revealed type is "builtins.list[builtins.type]"

While this is perhaps less precise than I'd hope (I'd hope to get list[type[Exception]]) it feels more right to me.

Adding an annotation to the variable (y: list[type[Exception]]) does help mypy see that this is ok, however in my original use-case the list being constructed was passed to a decorator function, so there was no easy opportunity to annotate it.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11

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 provided Python example with mypy 0.991 or a current checkout and compare the inferred types with and without ValueError. Trace the list-item inference and exception-type handling, then add a regression test showing that ImportError is accepted in the list and verify the expected revealed type.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.