Type narrowing when condition is assigned to a variable
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Narrowing techniques perform very well when the condition is calculated inside the if condition. When these are made outside, I can understand that mypy cannot guarantee that the narrow will be ok as the boolean value of the condition might be changed before reaching the if statement. However, when the value of this condition is given outside of the if statement but defined as a Final type, the narrow should be working
Minimal code to repdroduce it:
from typing import Optional, Final
def example_func(value: Optional[int] = None):
condition: Final = value is not None
if condition:
reveal_type(value) # Revealed type is "Union[builtins.int, None]"
value = value + 1 # MYPY ERROR
if value is not None:
reveal_type(value) # Revealed type is "builtins.int"
value = value + 1 # MYPY OK
return 0
Expected Behavior
The type of value for the first if statement should be builtins.int, as the condition variable should remain with the same value that was previously assigned to it.
Actual Behavior
Narrowed not performed, and thus the type of value is still inferred as Optional[int]
Your Environment
- Mypy version used: 0.931
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: Python 3.8.10
- Operating system and version: Ubuntu 20
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、mypy 0.931 で最小限の Python 例を実行し、Final 条件の周辺にある 2 つの reveal_type の結果を調べます。Final 変数に代入された条件に対する型の絞り込みの挙動を追跡します。最初の reveal_type が builtins.int を報告し、続く加算が、既存の直接条件に対する挙動を弱めることなく受け入れられれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers, devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100