python / python/mypy

Nested if Optional checking for class attributes fails

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

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

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

説明

Checking optional attributes in a class does not persist in a nested if:

(test.py)

#!/usr/bin/env python3

import typing


class Example:
    def __init__(self):
        self.a: typing.Optional[int]


def check_class(foo: Example, bar: Example):
    reveal_type(foo.a)
    if foo.a is not None:
        reveal_type(foo.a)
        if foo.a > 0:
            reveal_type(foo.a)
            foo = bar
        elif foo.a < 0:
            reveal_type(foo.a)
            foo.a += 1

Output:

$ mypy test.py
test.py:12: note: Revealed type is "Union[builtins.int, None]"
test.py:14: note: Revealed type is "builtins.int"
test.py:16: note: Revealed type is "builtins.int"
test.py:18: error: Unsupported operand types for > ("int" and "None")
test.py:18: note: Left operand is of type "Optional[int]"
test.py:19: note: Revealed type is "Union[builtins.int, None]"
test.py:20: error: Unsupported operand types for + ("None" and "int")
test.py:20: note: Left operand is of type "Optional[int]"

Environment

  • Python 3.9.9
  • mypy == 0.971
  • Linux x86_64
  • No other mypy config

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

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

はじめの一歩

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

調査の方向性

まず、提供された test.py の例を mypy で実行し、ネストされた分岐での reveal_type の出力と報告されたエラーを調べます。foo の再代入後に誤った narrowing を導入することなく、意図した non-None の narrowing がそこで一貫して処理されれば、作業は完了です。

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

評価

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

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

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