python / python/mypy

Mypy fails to type check function signature after plugin pass

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

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

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

説明

Bug Report

I wrote a plugin to replace types, but Mypy fails to typecheck after my changes. I start off trying to fix the type error in this signature with a plugin:

def almost_id(a: str) -> str:
    return int(a)

almost_id("6")

with my plugin:

def replace_str(self, ctx: FunctionSigContext) -> FunctionLike:
        api = ctx.api

        new_signature = ctx.default_signature.copy_modified(
            ret_type=api.named_type('builtins.int')
        )

        un_anal = new_signature.definition.unanalyzed_type.copy_modified(
            ret_type = api.named_type('builtins.int')
        )

        new_signature.definition.unanalyzed_type = un_anal

        typ = new_signature.definition.type.copy_modified(
            ret_type = api.named_type('builtins.int')
        )

        new_signature.definition.type = typ

        return new_signature

I have tried going through the attrs of the functionsigcontext, api and the expr_checker but can't seem to find some other functionality to either:

  • force mypy to proceed with type checking
  • modify the existing type analysis or map
  • delay type checking until the plugin mods have been completed, something like defer() in the semantic analyzer.

To Reproduce
gist: https://gist.github.com/dibrinsofor/bddcbd2eedbb233b131bb1b8d562369a

mypy tests/str_int.py

Expected Behavior

I expect mypy to pass

Actual Behavior

tests/str_int.py:2: error: Incompatible return value type (got "int", expected "str")  [return-value]

even though printing the new signature returns:

def (a: builtins.str) -> builtins.int

Your Environment

  • Mypy version used: 1.14.0+dev.8c7db13f71098a6facea66ab165b6bc3ef688bdf
  • Mypy command-line flags: --show-traceback
  • Python version used: Python 3.11.5

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

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

はじめの一歩

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

調査の方向性

gist の再現例を使って mypy tests/str_int.py を実行し、報告されたエラーと replace_str の後に出力されるシグネチャを比較します。レポートで言及されている expr_checkerdefer() の経路を使い、意味解析と式チェックの際に FunctionSigContext の結果がどのように消費されるかを追跡します。プラグインによって変更された戻り値の型が尊重され、再現例がパスすれば完了です。

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

評価

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

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

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