Non-optional send types and the Generator.send() parameter
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
Python doesn’t allow you to send a non-None value to a just-started generator, but if the send type of a generator is not annotated Optional then .send(None) can’t be used.
You could just use next() at the start, but a situation can be created where Python and Mypy don’t agree on a type error. Pyright behaves similarly.
I’m not sure what the solution is here. This issue might require discussion.
To Reproduce
$ cat file1.py
from collections.abc import Generator
def g() -> Generator[int, int, None]:
sent = 0
while True:
sent = yield sent
gen = g()
print(gen.send(0)) # <--
print(gen.send(1))
print(gen.send(2))
$ mypy --strict file1.py
Success: no issues found in 1 source file
$ python3 file1.py
Traceback (most recent call last):
File "/Users/danpro/Desktop/fold/file1.py", line 10, in <module>
print(gen.send(0)) # <--
TypeError: can't send non-None value to a just-started generator
$
$
$ cat file2.py
from collections.abc import Generator
def g() -> Generator[int, int, None]:
sent = 0
while True:
sent = yield sent
gen = g()
print(gen.send(None)) # <--
print(gen.send(1))
print(gen.send(2))
$ mypy --strict file2.py
file2.py:10: error: Argument 1 to "send" of "Generator" has incompatible type "None"; expected "int"
Found 1 error in 1 file (checked 1 source file)
$ python3 file2.py
0
1
2
Expected Behavior
A TypeError should not occur at runtime when Mypy reports successful type checking.
Actual Behavior
A TypeError occurs even though Mypy reports successful type checking.
My Environment
- Mypy version used: 0.910
- Python version used: 3.9.6
- Pyright version used: 1.1.163
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
2つの再現例 file1.py と file2.py に記述されている Generator.send() の型付け動作から始め、mypy の結果を Python の実行時 TypeError と比較します。Generator の send 型が初期の None 値をどのように扱うかを確認し、同等の Pyright の動作との相互作用を検討します。両方の例について意図した動作が確立され、実行時に直ちに失敗する可能性のあるコードを型チェッカーが受け入れなくなれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- 説明が足りない
- 初心者へのやさしさ
- 25/100