python / python/mypy

Add support for simple lambda type guard

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

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

feature priority-2-low topic-type-narrowing topic-typeguard-typeis
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Feature

Consider the following code:

from typing import Optional, List


list_with_none: List[Optional[int]] = [None, 1, 2]


filtered = filter(lambda v: v is not None, list_with_none)
reveal_type(filtered)
# Revealed type is 'typing.Iterator[Union[builtins.int, None]]'

It would be nice if mypy was able to parse simple lambda functions like this one, and infer that filtered is typing.Iterator[builtins.int].

Note that in this example, we use a simple none check, but this could work with more complicated checks:

list_of_tuples: List[Tuple[Optional[int], Optional[int]]]
filter(lambda v: v[0] is not None and v[1] is not None, list_of_tuples)
# would become `Iterator[Tuple[int, int]]`

Pitch

This is a fairly common idiom in Python.

Reasons why mypy might now want to do this:

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

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

はじめの一歩

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

調査の方向性

2つの filter/lambda の例と PEP 647 の参照から始め、要求された表示される型を比較し、どの単純な述語を対象に含めるかを判断します。完了条件は、None チェックの例で mypy が Iterator[int]、ペアチェックで Iterator[Tuple[int, int]] を推論し、サポートされるケースをカバーすることです。

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

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

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

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