Flow-sensitive typing ignores dictionary key mutation
オープン
まだ誰も着手していません。
bug
topic-type-narrowing
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
mypy allows runtime type checks for dictionary items. However it ignores subsequent dictionary mutations. This leads to mypy accepting code that fails at runtime.
To Reproduce
from typing import Dict, Optional
foo_dict: Dict[str, Optional[str]] = {'bar': 'baz'}
if foo_dict['bar'] is not None:
foo_dict['bar'] = None
foo_dict['bar'].upper()
Expected Behavior
mypy reports .upper() call as error. This is similar to what already happens with object attributes:
from dataclasses import dataclass
from typing import Optional
@dataclass
class Foo:
bar: Optional[str]
foo = Foo(bar='baz')
if foo.bar is not None:
foo.bar = None
foo.bar.upper()
For such code mypy outputs the following error: "None" has no attribute "upper".
Actual Behavior
mypy reports no error.
Your Environment
- Mypy version used: 0.812
- Mypy command-line flags:
--strict - Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.6.8
- Operating system and version: Windows 8.1
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、mypy --strict を使って Python の再現コードを実行し、dataclass 属性の例と比較して、辞書の場合は受け入れられる一方で属性の場合は拒否されることを確認します。辞書要素式に対するフロー依存の narrowing ロジックを追跡し、ミューテーションのカバレッジを追加します。mypy が .upper() の呼び出しをエラーとして報告すれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers, devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100