python / python/mypy

generic fails to narrow, something to do with using `NoReturn` on contravariant generic

Open
#11,508 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

from typing import Generic, Mapping, NoReturn, Sequence, TypeVar

T = TypeVar("T", contravariant=True)


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


foo = Foo[int]()
bar = Foo[str]()

a1: Sequence[Foo[NoReturn]] = [foo]  # no error
a2: Sequence[Foo[NoReturn]] = [bar]  # no error

# error (this one seemed to be fixed around commit 32448b88370f8327c390f4e21666065c87ca95e2, then broken again)
a3: Sequence[Foo[NoReturn]] = [foo, bar]

a4: Sequence[Foo[NoReturn]] = [foo] or [bar]  # error

a5: Mapping[str, Sequence[Foo[NoReturn]]] = {  # error
    "foo": [foo],
    "bar": [],  # error goes away if you change this to [foo]
}

a6: Sequence[Sequence[Foo[NoReturn]]] = [[foo], []]  # error

https://mypy-play.net/?mypy=latest&python=3.10&gist=175deca029e02ea95af74f7c4a02856c

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 six examples in the linked mypy-play reproduction and record the current diagnostics, especially for a3–a6. Compare the behavior with commit 32448b88370f8327c390f4e21666065c87ca95e2 as historical context. Done means the inconsistent errors for equivalent Foo[NoReturn] constructions are resolved without introducing new errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.