python / python/mypy

(🐞) Failure to narrow lambdas when using `Protocol` with `__call__`

Aperta
#16,797 1 commento 2 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 fails to narrow lambdas and detect errors when using a Protocol with a __call__ method, in situations where using the equivalent Callable formulation results in narrowing and error detection.

To Reproduce

In the following snippet, type narrowing is performed on the lambda function passed to the validator argument of validate10, resulting in the implementation typo being caught by Mypy:

from typing import Callable, TypeVar

InstanceT = TypeVar("InstanceT")

def validate10(instance: InstanceT, validator: Callable[[InstanceT, int], bool]) -> bool:
    return validator(instance, 10)

class MyClass:
    def validate(self, value: int) -> bool:
        return value >= 10

instance = MyClass()
validate10(instance, lambda self, value: self.validatez(value)) # Mypy error
# "MyClass" has no attribute "validatez"; maybe "validate"?

The following snippet is essentially equivalent to the above, but using Protocol in place of Callable. The type of the lambda function is no longer narrowed, and the implementation typo is not caught:

from typing Protocol, TypeVar

InstanceT = TypeVar("InstanceT")
InstanceT_contra = TypeVar("InstanceT_contra", contravariant=True)
class Validator(Protocol[InstanceT_contra]):

    def __call__(self, instance: InstanceT_contra, value: int, /) -> bool:
        ...

def validate10(instance: InstanceT, validator: Validator[InstanceT]) -> bool:
    return validator(instance, 10)

class MyClass:
    def validate(self, value: int) -> bool:
        return value >= 10

instance = MyClass()
validate10(instance, lambda self, value: self.validatez(value)) # No error

I would expect the narrowing behaviour in the two snippets to be the same (or close enough).
Please note that the issue persists even when the type variable is removed:

class MyClass:
    def validate(self, value: int) -> bool:
        return value >= 10

class Validator(Protocol):

    def __call__(self, instance: MyClass, value: int, /) -> bool:
        ...

def validate10(instance: MyClass, validator: Validator) -> bool:
    return validator(instance, 10)

instance = MyClass()
validate10(instance, lambda self, value: self.validatez(value)) # No error

Pylance/Pyright (strict) detects the typo in all cases.

Your Environment

  • Mypy version used: 1.7.1
  • Mypy command-line flags: --strict
  • 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

Inizia con le riproduzioni di Callable e Protocol relative a validate10, Validator e alla lambda passata a validator, confrontando i tipi dei parametri inferiti con --strict. Il lavoro è completo quando i casi basati su Protocol restringono la lambda come il caso Callable e segnalano l'attributo scritto erroneamente validatez, anche quando la variabile di tipo viene rimossa.

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
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.