python / python/mypy

Function's argument type inference is affected by the functions return type when in a comprehension

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

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

bug
主要言語
Python
スター
20.6k
フォーク
3.3k
平均マージ
1日 18時間
マージ済み PR(30日)
54

説明

Bug Report

MyPy seems to be getting confused if function that receives a generic class returns a union type with that generic is used in a comprehension. If the functions is used in a for loop or the function returns just the generic T, then MyPy doesn't show any errors.

To Reproduce

import dataclasses
from typing import Callable, TypeVar, Generic

T = TypeVar('T')


@dataclasses.dataclass(frozen=True, slots=True)
class Capsule(Generic[T]):
    builder: Callable[[], T]


def process(argument: Capsule[T]) -> T | RuntimeError:
    if isinstance((value := argument.builder()), int) and value % 2 != 0:
        return RuntimeError('Not an even number')

    return argument.builder()


encapsulated_ints = tuple(Capsule(builder=lambda: item) for item in range(10))

requests: list[int | RuntimeError] = []
for encapsulated_int in encapsulated_ints:
    request = process(encapsulated_int)
    requests.append(request)
requests = list(process(encapsulated_int) for encapsulated_int in encapsulated_ints)

Error:

main.py:25: error: Argument 1 to "process" has incompatible type "Capsule[int]"; expected "Capsule[int | RuntimeError]"  [arg-type]

https://mypy-play.net/?mypy=latest&python=3.12&gist=ffe7822cc564a6f347c2b8d6fd98c47f

Expected Behavior

The list comprehension line should be interpreted exactly the same as the for loop.

Actual Behavior

MyPy somehow relates the function return to the generic type.

Your Environment

  • Mypy version used: 1.9.0
  • Mypy command-line flags: no flags
  • Mypy configuration options from mypy.ini (and other config files): no configs
  • Python version used: 3.12

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

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

はじめの一歩

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

調査の方向性

issue にある Python の再現コードから始め、for ループとジェネレータ内包表記の診断を比較します。各ケースで、ジェネリック引数の推論が関数の戻り値型をどのように使用するかを追跡します。内包表記がループと同様に受け入れられ、回帰テストで報告された例がカバーされれば完了です。

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

評価

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

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

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