python / python/mypy

`Never` inferred in complex situation with variadic callable protocol

Offen
#16,522 4 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-pep-646
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

Mypy is inferring a Never in a bit of a complicated setup involving TypeVarTuple, __call__ protocols and a regular TypeVar. If an annotated assignment is present it is able to check that they match. But when a bare call is done, it infers Never and always produces an error. This is a simplified version of Trio's Nursery.start() async spawn method, which I'm trying to type. (See src/trio/_core/_run.py.) I simplified it a little, removing an overload and making it synchronous.

To Reproduce

from typing import Generic, TypeVar, Protocol
from typing_extensions import TypeVarTuple, Unpack

PosArgT = TypeVarTuple("PosArgT")
StatusT = TypeVar("StatusT")
StatusT_co = TypeVar("StatusT_co", covariant=True)
StatusT_contra = TypeVar("StatusT_contra", contravariant=True)

class TaskStatus(Generic[StatusT_contra]):
    def started(self, value: StatusT_contra) -> None: ...

class NurseryStartFunc(Protocol[Unpack[PosArgT], StatusT_co]):
    def __call__(
        self,
        *args: Unpack[PosArgT],
        task_status: TaskStatus[StatusT_co],
    ) -> object: ...

def nursery_start(
    async_fn: NurseryStartFunc[Unpack[PosArgT], StatusT],
    *args: Unpack[PosArgT],
) -> StatusT:  ...

def task(a: int, b: str, *, task_status: TaskStatus[set[str]]) -> None: ...

def test() -> None:
    a_task: NurseryStartFunc[int, str, set[str]] = task  # task implements the protocol
    result: set[str] = nursery_start(task, 1, "b")  # If result is annotated this works.
    result = nursery_start(task, "a", 2)  # Detects invalid call correctly
    # Without assignment or if unnanotated, infers Never as return type?
    nursery_start(task, 1, "b")

https://mypy-play.net/?mypy=latest&python=3.11&gist=31be4208e294eb6c5cbc7390f4a836f4

Expected Behavior

Ideally Mypy would be able to propagate the typevar in TaskStatus to determine the return type, and verify that appropriate types were passed for *args.

Actual Behavior

(Last two statements)
main.py:39: error: Argument 1 to "nursery_start" has incompatible type "Callable[[int, str, NamedArg(TaskStatus[set[str]], 'task_status')], None]"; expected "NurseryStartFunc[str, int, set[str]]"  [arg-type]
main.py:41: error: Argument 1 to "nursery_start" has incompatible type "Callable[[int, str, NamedArg(TaskStatus[set[str]], 'task_status')], None]"; expected "NurseryStartFunc[int, str, Never]"  [arg-type]

The first error is correct, showing that Mypy can understand the types somewhat. But in the second case it's strangely producing Never, when it should really be effectively Any - the type is unused so it doesn't matter what it is.

Your Environment

  • Mypy version used: 1.7.0, also tried master
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.8, 3.11

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Führe die bereitgestellte Python-Reproduktion mit dem verlinkten mypy-play-Beispiel aus und vergleiche die annotierten und bare-call-Fälle. Beginne damit, die Typinferenz für TypeVarTuple, das Callable-Protokoll und TaskStatus in diesem Beispiel nachzuverfolgen. Die Aufgabe ist erledigt, wenn der gültige bare call nicht mehr ein inferiertes Never meldet, während die ungültige Argumentreihenfolge weiterhin abgelehnt wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.