python / python/mypy

Constant vs variable as index for none-checking List[Optional[...]]

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

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

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

説明

Can you explain to me why there is this difference between using a constant and a variable as index for none-checking here?

from typing import List, Optional

my_list: List[Optional[float]] = []

if my_list[0] is not None:
    result_1: float = my_list[0]        # no error
    result_2: float = my_list[1]        # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")

id_0 = 0
if my_list[id_0] is not None:
    result_3: float = my_list[id_0]     # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")


for i in range(10):
    if my_list[i] is not None:
        a: float = my_list[i]           # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")
  • Mypy version used: 0.800 0.941
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: python3.6
  • Operating system and version: Ubuntu 18.04 in WSL2 (Windows 11)

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

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

はじめの一歩

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

調査の方向性

この issue ではリポジトリのファイルやテストが指定されていません。mypy 0.941 で例を再現し、続いてインデックス付きの List[Optional[float]] 式に対する型の絞り込みの挙動を追跡してください。定数、変数、ループインデックスで挙動が異なる理由を説明でき、バグであることが確認された場合は、適切な regression test でカバーできれば完了です。

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

評価

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

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

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