python / python/mypy

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

オープン
#16,797 コメント 1 件 リアクション 2 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

validate10、Validator、および validator に渡される lambda をめぐる Callable と Protocol の再現ケースから始め、--strict 下で推論されたパラメーター型を比較します。Protocol ベースのケースが Callable のケースと同じように lambda を絞り込み、型変数を削除した場合も含めて、スペルミスのある validatez 属性を報告すれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。