python / python/mypy

Mypy fails to deduce generic type if it has been previously deduced as `<nothing>`

Offen
#13,250 0 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Bug Report

Mypy fails to deduce generic type if it has been previously deduced as <nothing>

To Reproduce

Minimal example to reproduce

from typing import Callable, TypeVar, Generic

T = TypeVar("T")

class Foo(Generic[T]):
    pass

def decorate(foo: Foo[T] | None) -> Callable[[T], T]:
    raise NotImplementedError


# Case 1
reveal_type(decorate(None)(str()))  # Revealed type is "<nothing>"; Argument 1 has incompatible type "str"; expected <nothing>

# Case 2
reveal_type(decorate(Foo())(str()))  # Revealed type is "<nothing>"; Argument 1 has incompatible type "str"; expected <nothing>

# Case 3
reveal_type(decorate(Foo[str]())(str()))  # Revealed type is "builtins.str"

Playground link

Expected Behavior

I'am expecting mypy to work in case 1 and case 2 like in the following example, where generic variable T isn't constrainted
by upper function decorate and her arguments.

def decorate() -> Callable[[T], T]:
    raise NotImplementedError

reveal_type(decorate()(str()))  # Revealed type is "str"

This intuition comes from the fact, that in some cases generic variables is not deductible at some point, but later they are defined through context of usage, like in the following example:

l = []  # it's is like `list[<nothing>]` right now
l.append(int())
reveal_type(l)  # Revealed type is `builtins.list[builtins.int]`

Actual Behavior

Mypy rejects case 1 and case 2 from the main example, but it's look counter-intuitive, therefore it looks like a bug

Your Environment

All examples were run on mypy-play.net using Python 3.10 and mypy == 0.971 without additional options

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

Start with the minimal examples in the issue and run them in mypy-play.net using Python 3.10 and mypy 0.971. Investigate why T remains <nothing> in cases 1 and 2; done means those cases infer str like case 3 and the no-argument example without rejecting the call.

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
Klar beschrieben
Anfängerfreundlichkeit
42/100

Neue Issues direkt in Ihr Postfach

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