python / python/mypy

False positive with variable key in Mapping with Optional value

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

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

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

説明

Bug Report

When using a mapping with an Optional value type, accessing a value using a variable key instead of a literal key prevents a None check from working properly.

To Reproduce

  1. Put the following code in test.py:
from typing import Mapping, Optional

FOO: str = "foo"

def func(text: str) -> None:
    _ = text

data: Mapping[str, Optional[str]] = {FOO: "bar"}

if data[FOO] is not None:
    func(data[FOO])  # Line 11

if data["foo"] is not None:
    func(data["foo"])
  1. Run mypy test.py

Expected Behavior

mypy should not output any errors. As the above example shows, using a string literal instead of a variable containing a string does not cause any errors, even though the code is otherwise identical. The "Optional types and the None type" section of the documents says "supported checks for guarding against a None value include if x is not None", so this code should work.

Actual Behavior

mypy outputs the following:

test.py:11: error: Argument 1 to "func" has incompatible type "Optional[str]"; expected "str"  [arg-type]

Your Environment

  • Mypy version used: 0.812
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): show_error_codes = True
  • Python version used: 3.7.9
  • Operating system and version: macOS 10.15.7 (19H524)

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

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

はじめの一歩

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

調査の方向性

test.py の再現コードから始め、mypy test.py を実行して、可変キーの場合とリテラルキーの場合で挙動が異なることを確認します。Mapping へのアクセスと Optional の絞り込みに関する型チェックの経路を追跡し、その後、可変キーの場合をカバーするリグレッションテストを追加します。両方のガード内の呼び出しがエラーなしで型チェックを通れば完了です。

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

評価

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

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

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