python / python/mypy

Wrong inference for `abs/__abs__` or function that calls a method on a generic type.

Aperta
#19,609 0 commenti 2 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

This was discussed in the typing forums.

Here mypy (latest version 1.17.1) infers the type of abs(value) incorrectly:

from typing import Self

class Real:
    def __abs__(self) -> Self:
        return self

def my_abs[T: Real](value: T):
    reveal_type(abs(value))      # Real
    reveal_type(value.__abs__()) # T

That is:

$ mypy z.py 
z.py:8: note: Revealed type is "z.Real"
z.py:9: note: Revealed type is "T`-1"
Success: no issues found in 1 source file

Since abs just calls __abs__ they return the same type which should be inferred as T in both cases.

I show the simpler example above with a concrete Real type but what I actually want to do is have a Protocol for abs:

from typing import Self, Protocol

class HasAbs(Protocol):
    def __abs__(self) -> Self:
        return self

def my_abs[T: HasAbs](value: T) -> T:
    return abs(value)

However mypy incorrectly rejects this because it infers the type of abs(value) incorrectly:

$ mypy z.py 
z.py:8: error: Incompatible return value type (got "HasAbs", expected "T")  [return-value]
Found 1 error in 1 file (checked 1 source file)

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 gli esempi z.py nell’issue ed esegui mypy 1.17.1 per riprodurre i diversi tipi rivelati e il valore restituito rifiutato. Traccia come viene inferito abs(value) rispetto a value.abs(), quindi aggiungi un test di regressione che mostri che un valore generico vincolato da HasAbs mantiene il tipo T e supera il controllo dei tipi.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.