Inconsistent handling of unsolved TypeVars
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
PEP 484 doesn't provide much clarity about the situation where a TypeVar is provided with no value in a generic function call, so I'm not sure if there is a "correct" behavior. However, I'd expect that the behavior would at least be consistent for a type checker.
from typing import Optional, TypeVar
T1 = TypeVar("T1")
def func1(suffix: Optional[T1] = ...) -> T1:
...
T2 = TypeVar("T2", bound=str)
def func2(suffix: Optional[T2] = ...) -> T2:
...
T3 = TypeVar("T3", str, bytes)
def func3(suffix: Optional[T3] = ...) -> T3:
...
T4 = TypeVar("T4", bytes, str)
def func4(suffix: Optional[T4] = ...) -> T4:
...
reveal_type(func1()) # <nothing>
reveal_type(func2()) # <nothing>
reveal_type(func3()) # str
reveal_type(func4()) # bytes
Note that mypy's results depend on whether the TypeVar is bound or constrained. If it is constrained, mypy appears to (arbitrarily?) choose the first constrained type.
Note that this situation arises in some common situations like the following:
from tempfile import mkstemp
_, temp_path = mkstemp()
reveal_type(temp_path) # str?
Like I said, I'm not sure what the "correct" or intended behavior is in this case, but the current behavior strikes me as inconsistent.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Es werden keine Dateien oder Tests genannt. Beginne damit, die vier generischen Funktionsbeispiele und den Fall mkstemp() zu reproduzieren, und vergleiche dann die abgeleiteten Typen für uneingeschränkte, gebundene und eingeschränkte TypeVars. Als abgeschlossen gilt die Aufgabe, wenn ein vereinbartes und konsistentes Verhalten feststeht, gefolgt von der Implementierung und einer Abdeckung durch Regressionstests.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Muss geklärt werden
- Anfängerfreundlichkeit
- 25/100