python / python/mypy

constrained TypeVar does not allow default of one of the constraint choices

Aperta
#18,017 2 commenti 6 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

I suspect this is related to https://github.com/python/mypy/issues/3737 but seems to be a specific sub-case that should be unambigious (and pyright accepts the code unchanged)

Bug Report

a constrained TypeVar T: (U, V) "T must be either U or V" does not accept either U or V as a default value

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=b7cc5486d300e5869277d59fa33a2b03

class U: pass
class V: pass

class C[T: (U, V)]:
    def __init__(self, tp: type[T] = U) -> None:
        self.x: dict[int, T] = {1: tp()}

(I kinda understand that mypy wouldn't know well enough that C() would actually be C[U] -- I've omitted overloads that make that work with mypy -- but the error on the default parameter still remains)

Expected Behavior

(no errors)

Actual Behavior

main.py:5: error: Incompatible default for argument "tp" (default has type "type[U]", argument has type "type[V]")  [assignment]
Found 1 error in 1 file (checked 1 source file)

I'm guessing that for a constrained typevar mypy is just checking each possible constraint against the default value?

Your Environment

  • Mypy version used: 1.12.1
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.12.x

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

Riproduci l'esempio di TypeVar vincolato della pagina mypy-play collegata con mypy 1.12.1, quindi traccia il percorso del controllo dei tipi per l'argomento predefinito. Aggiungi un test di regressione che copra i valori predefiniti di entrambe le opzioni di vincolo e verifica che l'esempio non segnali errori.

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.