python / python/mypy

Generic callback protocols break with kwargs

オープン
#7,311 コメント 10 件 リアクション 0 件 担当者 0 名 GitHub で見る

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

needs discussion topic-calls topic-protocols
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

I'm getting an unexpected error when using callback protocols with kwargs

Normal callback with no args or kwargs works fine:

from typing import *

T1 = TypeVar('T1')
T2 = TypeVar('T2')

T_contra = TypeVar('T_contra', contravariant=True)
T_co = TypeVar('T_co', covariant=True)

class Callback(Protocol[T_contra, T_co]):
  def __call__(self, __element: T_contra) -> T_co:
    pass

def applyit(func: Callback[T1, T2], y: T1) -> T2:
    return func(y)

def callback(x: str) -> int:
    pass

applyit(callback, 'foo')  # OK!

callback with args works fine:

from typing import *

T1 = TypeVar('T1')
T2 = TypeVar('T2')

T_contra = TypeVar('T_contra', contravariant=True)
T_co = TypeVar('T_co', covariant=True)

class CallbackWithArgs(Protocol[T_contra, T_co]):
  def __call__(self, __element: T_contra, *args: Any) -> T_co:
    pass

def applyit_with_args(func: CallbackWithArgs[T1, T2], y: T1) -> T2:
    return func(y)

def callback_with_args(x: str, *args: Any) -> int:
    pass

applyit_with_args(callback_with_args, 'foo')  # OK!

But the same thing with kwargs produces an error:

from typing import *

T1 = TypeVar('T1')
T2 = TypeVar('T2')

T_contra = TypeVar('T_contra', contravariant=True)
T_co = TypeVar('T_co', covariant=True)

class CallbackWithKwargs(Protocol[T_contra, T_co]):
  def __call__(self, __element: T_contra, **kwargs: Any) -> T_co:
    pass

def applyit_with_kwargs(func: CallbackWithKwargs[T1, T2], y: T1) -> T2:
    return func(y)

def callback_with_kwargs(x: str, **kwargs: Any) -> int:
    pass

# Argument 1 to "applyit_with_kwargs" has incompatible type "Callable[[str, KwArg(Any)], int]"; expected "CallbackWithKwargs[str, <nothing>]"
applyit_with_kwargs(callback_with_kwargs, 'foo')  # Error!

Perhaps this is expected behavior and I'm just overlooking some subtle interplay between the args in the last case, but it seems like a bug.

mypy 0.720

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

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

はじめの一歩

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

調査の方向性

提供された callback protocol の再現コードを、報告された mypy 0.720 の挙動で実行し、引数なし、*args、**kwargs のケースを比較します。診断の原因となっている型推論と callback 互換性の経路を追跡し、その後、kwargs callback が戻り値の型を失わずに受け入れられることを示す回帰テストを追加します。

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

評価

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

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

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