python / python/mypy

Partial specialization of a generic type

Aperta
#14,262 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

I have have a generic class hierarchy, mirroring the hierarchy of the type parameter. I am trying to add proper type annotations to these classes.

In the example below (gist here) I'm attempting to partially specialize the Root class:

from typing import Generic, TypeVar

_T = TypeVar("_T")

class Root(Generic[_T]):
    def __init__(self, value: _T):
        self.value = value

_Number = TypeVar("_Number", int, float)

class FooNumber(Root[_Number]):
    def __init__(self, value: _Number):
        super().__init__(value)

... mypy reports on the __init__ upcall from FooNumber.__init__():

test-mypy-typevar-inherit.py:13: error: Argument 1 to "__init__" of "Root" has incompatible type "int"; expected "_Number"  [arg-type]
test-mypy-typevar-inherit.py:13: error: Argument 1 to "__init__" of "Root" has incompatible type "float"; expected "_Number"  [arg-type]

The goal is to then declare FooInt deriving from FooNumer[int] (and similarly for FooFloat).
A direct specialization of FooInt from Root[int] shows (as expected) no issue, and I don't feel it's very clear why this FooNumber definition causes any problem.

It seems there would be no reason for those errors.

Note: this point was first raised on Gitter and on stackoverflow

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 con il riproduttore mypy-play collegato e con l’esempio mostrato di ereditarietà generica, quindi esamina come mypy verifica l’upcall a FooNumber.init(). Il lavoro è completato quando la specializzazione parziale non produce più gli errori incompatible-type segnalati, mentre FooInt e FooFloat possono specializzare FooNumber come previsto.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
5/5
Tempo stimato
Più di una settimana
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.