Decorator with constrained TypeVar specializes to first constraint
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
Changing the order of constraints of TypeVar T changes whether or not mypy passes. The wrapped method always gets narrowed to whatever the first constraint type is set to.
To Reproduce
from collections.abc import Callable
from typing import TypeVar, reveal_type
T = TypeVar("T", str, bytes) # fails
# T = TypeVar("T", bytes, str) # passes
def decorator(fn: Callable[[T], T]) -> Callable[[T], T]:
def wrapped(data: T) -> T:
return fn(data)
return wrapped
@decorator
def process(data: T) -> T:
return data
b: bytes = b"test"
result = process(b)
Or see mypy playground: https://mypy-play.net/?mypy=latest&python=3.12&gist=12fd2e05764d26a16cd1d16a10897671
Expected Behavior
Ideally pass for both versions, or consistently fail regardless of the constraint order.
On pyright playground the revealed types match my expectations and pass with either TypeVar order
Actual Behavior
mypy passes or fails depending on TypeVar constraint order, or the data input type
Your Environment
Same behavior with all tested mypy versions (1.6.0 .. 1.19.1) and python 3.11+
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
Beginne damit, den minimalen Reproduzierer für den Decorator und das eingeschränkte TypeVar aus dem Issue auszuführen, und verfolge dann, wie mypy die Spezialisierung der Constraints und die umschlossene aufrufbare Funktion verarbeitet. Die Aufgabe ist abgeschlossen, wenn das Ergebnis nicht mehr von der Reihenfolge der TypeVar-Constraints abhängt und Tests für beide Constraint-Reihenfolgen vorhanden sind.
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