python / python/mypy

Generic type inferred wrong; curious difference betweer `aiter(f(x))` and `c = f(x); aiter(c)`

Offen
#16,376 13 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-type-context
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

Consider this code (playground):

from typing import TypeVar, Generic, Callable, Coroutine, Any, AsyncIterator

_T = TypeVar("_T")

class StartedToken:
    pass

class ProducerContext(Generic[_T]):
    pass

async def coro_to_aiter(
    coroutine: Callable[[ProducerContext[_T]], Coroutine[Any, Any, None]]
) -> AsyncIterator[_T | StartedToken]:
    yield StartedToken()

async def coro(ctx: ProducerContext[int]) -> None:
    pass

# Split into two lines, no error:
c = coro_to_aiter(coro)  # no error
it = aiter(c)  # no error

# The same on one line -> mypy error:
it2 = aiter(coro_to_aiter(coro))  # error: Argument 1 to "coro_to_aiter" has incompatible type ...

Expected Behavior

I would expect mypy to not error on the it2 definition line. Moreover, regardless of whether mypy can handle these definitions, I would expect to see the same behavior (error or absence of error) in the "Split into two lines" case and the "on one line" case.

Actual Behavior

I get this error on the it2 line, and no errors on other lines:

main.py:24: error: Argument 1 to "coro_to_aiter" has incompatible type "Callable[[ProducerContext[int]], Coroutine[Any, Any, None]]"; expected "Callable[[ProducerContext[int | StartedToken]], Coroutine[Any, Any, None]]" [arg-type]

Your Environment

  • Mypy version used: 1.6.1 (playground), current master
  • Python version used: 3.11, 3.12

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

Beginne mit dem main.py-Reproducer aus dem Issue, verwende die aufgeführten Python- und mypy-Versionen und vergleiche die Fälle mit aufgeteiltem und verschachteltem aiter(coro_to_aiter(coro)). Verfolge, wie die generische Typinferenz jeden Aufruf behandelt, und füge einen fokussierten Regressionstest für die Abweichung hinzu oder aktualisiere ihn. Erledigt ist die Aufgabe, wenn beide Formen konsistente, erwartete Diagnosen erhalten.

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
42/100

Neue Issues direkt in Ihr Postfach

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