python / python/mypy

Mypy fails to infer the type of the decorated function used in the decorator

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

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

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

説明

Hi mypy team,

Bug Report
I'm looking into the issue with design-by-contract library icontract which heavily uses decorators to formalize contracts. For many functions and methods, the contracts involve the decorated function (or method) itself.

See the example from the issue https://github.com/Parquery/icontract/issues/243:

from icontract import ensure

@ensure(
    lambda a, b, result: 
    result == myadd(b, a), 
    "Commutativity violated!"
)
def myadd(a: int, b: int) -> int:
    return a + b

Mypy 0.960 says:

tests_3_10\deleteme.py:5: error: Cannot determine type of "myadd"

If I add # type: ignore:

from icontract import ensure

@ensure(
    lambda a, b, result: 
    result == myadd(b, a),   # type: ignore
    "Commutativity violated!"
)
def myadd(a: int, b: int) -> int:
    return a + b

mypy does not complain any more.

I was actually a bit surprised that mypy tried to infer the types in the lambda. @claudio-ebel tried a couple of fixes using casting (see his comment https://github.com/Parquery/icontract/issues/243#issue-1229622746), but none of them worked.

I am actually not sure if this is a misunderstanding on our part or a bug in mypy. Any pointers about how to resolve the issue are very much appreciated! Please let us know if you need more information, or if there is anything we can do to help to fix this.

Your Environment

  • Mypy version used: 0.960
  • Mypy command-line flags: `--strict``
  • Python version used: 3.10.0

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

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

はじめの一歩

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

調査の方向性

まず、提供された icontract の例を mypy 0.960 と --strict を使って再現し、次に、エラーに関係するデコレータとラムダの型推論のエントリーポイントを追跡します。type: ignore コメントがある場合とない場合の動作を比較します。診断が想定されたものかどうかを判断するか、その抑制なしで例がチェックされるように推論を修正できれば完了です。

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

評価

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

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

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