python / python/mypy

TypeVar bound doesn't understand CRTP

Aperta
#17,613 2 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

Bug Report

Ideally, this snippet would work. It enables making multiple types that share the same implementation but don't subclass each other (like newtype in other languages). If you comment out the other.quack() call and the bound="Foo[DerivedT]") then it will typecheck -- the issue is specifically with being able to express a typevar bound indicating the typevar has a base class that uses that typevar as a generic parameter.

#!/usr/bin/env python

from __future__ import annotations
from typing import Generic, TypeVar

DerivedT = TypeVar("DerivedT", bound="Foo[DerivedT]")

class Foo(Generic[DerivedT]):
    def quack(self) -> None:
        print("quack!")

    def quack_together(self, other: DerivedT) -> None:
        self.quack()
        other.quack()

class Bar(Foo[Bar]): pass

x = Bar()
y = Bar()

x.quack_together(y)
$ python -m mypy --strict /tmp/self_test.py 
self_test.py:6: error: Type variable "self_test.DerivedT" is unbound  [valid-type]
self_test.py:6: note: (Hint: Use "Generic[DerivedT]" or "Protocol[DerivedT]" base class to bind "DerivedT" inside a class)
self_test.py:6: note: (Hint: Use "DerivedT" in function signature to bind "DerivedT" inside a function)
Found 1 error in 1 file (checked 1 source file)
  • Mypy version used: mypy 1.10.0 (compiled: yes)
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

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

Il reproducer si trova in /tmp/self_test.py; inizia eseguendo python -m mypy --strict /tmp/self_test.py con il bound CRTP mostrato. Verifica come mypy segnala la TypeVar non associata e considera completato il lavoro quando l'esempio supera il type-checking senza quell'errore, preservando la relazione tra i tipi descritta.

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

Valutazione

Stack tecnologico
python
Ambito
compilers
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.