python / python/mypy

Specialized methods on generic classes

Aperta
#14,243 1 commento 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

Let's say I have a generic class G.

from __future__ import annotations

from collections.abc import Sized
from typing import Generic, TypeVar

T = TypeVar("T")

class G(Generic[T]):
    pass

I want to have a single method on this class that's only legal for a subset of T.

If I want to limit it to, say, int, it works:

class G(Generic[T]):
    def test(self: G[int]) -> G[int]:
        return self

G[int]().test()  # Works, as it should
G[str]().test()  # Error, as it should

But if I want to limit it to, say, a protocol like Sized, I get a false negative:

S = TypeVar("S", bound=Sized)

class G(Generic[T]):
    def test(self: G[S]) -> G[S]:
        return self


G[int]().test()  # False negative - works, but it shouldn't

This is a pity, since it'd unlock some cool features I was working on vis-a-vis using attrs attributes. Are there any workarounds? Would this be handled by intersection types maybe?

Your Environment

  • Mypy version used: mypy 1.0.0+dev.b8c03ab6809aab56928f3cd865edb44944a600a2
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: Python 3.10.6

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 Python fornito con la versione di mypy indicata e confronta il comportamento della specializzazione int con quello della specializzazione vincolata da Sized. Traccia il percorso di controllo del self-type generico, quindi aggiungi o aggiorna un test di regressione in modo che i metodi specializzati vincolati da un protocollo vengano accettati o rifiutati in base al comportamento previsto.

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

Valutazione

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