python / python/mypy

Wrong type inference with "yield from" from an Iterator class

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

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

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

説明

Bug Report

When using "yield from" for an iterable instance the type inference if wrong. Normal for-loop iteration over the same iterable does work though.

To Reproduce

from typing import Iterator, Self


class goes_to_11(Iterator[int]):
    def __init__(self):
        self.elevens = iter((11,))

    def __next__(self) -> int:
        return next(self.elevens)

    def __iter__(self) -> Self:
        return self


def bunch_of_11() -> Iterator[tuple[int, ...]]:
    yield from goes_to_11()

    for integer in goes_to_11():
        yield integer


for value in bunch_of_11():
    print(type(value), value)

Expected Behavior

Mypy should complain about both the "yield from" line and the "yield integer" line, but for the former it doesn't.

Actual Behavior

mypy --strict buggy.py
buggy.py:19: error: Incompatible types in "yield" (actual type "int", expected type "tuple[int, ...]")  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

Tested on Linux Python 3.12.3 using mypy wheel mypy-1.11.0+dev.b88fdbd32fe0a45d40531a6504317aa3fd48489e-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

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

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

はじめの一歩

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

調査の方向性

まず、提供されている buggy.py の再現コードを mypy --strict で実行し、yield from 行とそれに続く for ループを比較します。Iterator[int] インスタンスの型推論を追跡します; 両方の経路について mypy が同じ incompatible-yield エラーを報告すれば完了です。

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

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
42/100

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

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