python / python/mypy

generic subclasss and typevar with constraint

Aperta
#7,362 10 commenti 7 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Not sure if this is a "bug" or I didn't understand generics, but

import typing

T = typing.TypeVar('T', str, int)


class Base(typing.Generic[T]):

    def __init__(self, bar: T):
        self.bar: T = bar


class Child(Base[T]):

    def __init__(self, bar: T):
        super().__init__(bar)

mypy 0.720 (on windows) says

> mypy.exe test\__init__.py
test\__init__.py:15: error: Argument 1 to "__init__" of "Base" has incompatible type "str"; expected "T"
test\__init__.py:15: error: Argument 1 to "__init__" of "Base" has incompatible type "int"; expected "T"

but if I change the T definition to T = typing.TypeVar('T') the errors go away

What I want is to specify that

  • the "Base" constructor has a parameter that could be an int or a str
  • the "Child" constructor has the same "signature" of the "Base" one (well, this is a simplified example, I want something more...)

is this a bug? di I misinterpreted the TypeVar usage?

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 in test_init_.py con mypy 0.720, confrontando il TypeVar vincolato con la versione non vincolata. Leggi i percorsi rilevanti per i generics e per il controllo di TypeVar, quindi stabilisci se la diagnostica segnalata è prevista; il lavoro è completato quando il comportamento è documentato oppure viene aggiunto un test di regressione e il problema viene corretto se si tratta di un bug.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.