python / python/mypy

False positive typing.Self has incompatible type when method uses class' generic type

Aperta
#16,871 4 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

mypy seems to get confused about type of typing.Self, when class is also typing.Generic, inside methods if a parameter has
the same type as the class Generic's TypeVar.

To Reproduce

from collections.abc import Awaitable, Callable
from typing import Generic, Self, TypeVar

AttributeValueT = TypeVar("AttributeValueT")


class Attribute(Generic[AttributeValueT]):
    def __init__(self, on_changed: Callable[[Self], Awaitable[None]]) -> None:
        self._on_changed = on_changed

    async def bar(self, _: AttributeValueT) -> None:
        # Argument 1 has incompatible type "Attribute[AttributeValueT]"; expected "Self"  [arg-type]
        await self._on_changed(self)  # type: ignore[arg-type]

Expected Behavior

I expect self / Self to have the correct type and to be able to avoid # type: ignore[arg-type]

Actual Behavior

See mypy error is in method comment above; error only makes sense with code as context.

Your Environment

  • Mypy version used: mypy 1.8.0 (compiled: yes)
  • Python version used: 3.11.7

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 fornito con mypy 1.8.0 e conferma l'errore di tipo incompatibile che coinvolge typing.Self e l'AttributeValueT generico. Traccia la gestione di Self per i metodi nelle classi Generic, quindi aggiungi un test di regressione che dimostri che self viene accettato senza type ignore e che la suite di test passa.

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.