python / python/mypy

Decorator with constrained TypeVar specializes to first constraint

Aperta
#20,437 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-calls
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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+

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo il riproduttore minimo del decoratore e del TypeVar vincolato dell'issue, quindi segui la gestione da parte di mypy della specializzazione dei vincoli e della callable wrapped. Il lavoro è completato quando il risultato non dipende più dall'ordine dei vincoli del TypeVar, con una copertura per entrambi gli ordini dei vincoli.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
42/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.