Type narrowing for dict.get("key") is not None
オープン
まだ誰も着手していません。
feature
topic-type-narrowing
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
See Code and Explanation below
To Reproduce
from typing import TypedDict, Optional
class DictA(TypedDict):
my_value: str
class DictB(TypedDict, total=False):
my_optional_dict: Optional[DictA]
def test(arg: DictB) -> None:
if arg.get("my_optional_dict") is not None:
print(arg["my_optional_dict"]["my_value"])
Expected Behavior
According to the TypedDict, we have 3 cases for the Key my_optional_dict:
- The Dict did not have this Key (indicated by
total=False - The Value of this Key is
None - The Value of this Key is a
DictA
If we look at the if in the test function, it does 2 things:
- Check if the Dict contains this Key
- Check if the value is not None
This means, that the my_optional_dict of arg is always of the type DictA, so mypy should not see a problem here.
Actual Behavior
main.py:14: error: Value of type "Optional[DictA]" is not indexable [index]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.0.0
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.11.1
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、指定された Python 3.11 の例を使い、設定フラグなしで、提供されている TypedDict の再現コードを mypy で実行します。None チェック後に型チェッカーが arg.get("my_optional_dict") をどのように絞り込むかを追跡し、その後、インデックス可能性エラーなしで通過する test() ベースのリグレッションテストを追加します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100