python / python/mypy

Common checks and union-attr error

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

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

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

説明

Bug Report / Discussion

I want to write the code shown below where the types of the attributes are checked in a centralised consistent way to avoid duplication. However, this triggers the union-attr error because the type inference within the checking method doesn't propagate to the outer method.

I'm pretty sure that mypy can't (or won't) do anything about this, but I'm not clear about what the proper resolution for this is that avoids (too much) code duplication or lots of extra code (see below for potential workarounds). Maybe something needs to be documented (e.g. via this issue) and possibly added to the common issues.

To Reproduce

class X:
    def __init__(self, x: str | None = None) -> None:
        self.x = x

    def ready(self) -> bool:
        return isinstance(self.x, str) and bool(self.x)

    def show(self) -> None:
        if not self.ready():
            raise RuntimeError("Object is not configured")

        print(repr(self.x.split()))  # <-- union-attr error

This is a simple example where the duplication would be limited, but it's fairly easy to get into situations where the ready method is far more complicated, e.g. might need to check several fields or combinations of fields, and where it's reused many times. Note that the ready method is useful in its own right.

Expected Behavior

Should be ok, in an ideal world.

Actual Behavior

x.py:12: error: Item "None" of "str | None" has no attribute "split"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Potential Workarounds

Workarounds are to write one of the following:

    def show(self) -> None:
        if not self.ready():
            raise RuntimeError("Object is not configured")

        print(repr(self.x.split())  # type: ignore[union-attr]  # might ignore other potential errors

or

    def show(self) -> None:
        if self.x is None or not self.ready():  # Duplicates logic in ready method
            raise RuntimeError("Object is not configured")

        print(repr(self.x.split()))

or (as suggested in (https://github.com/python/mypy/issues/4805#issuecomment-1018892112))

    def show(self) -> None:
        if not self.ready():
            raise RuntimeError("Object is not configured")
        assert isinstance(self.x, str)  # Duplicates logic in ready method
        # although it's nice that this assert is skipped when using `python -O`

        print(repr(self.x.split())

or (as I think is suggested in https://github.com/python/mypy/issues/15207#issuecomment-1537519614)

    @property
    def x_checked(self) -> str:
        # Do I have to write a property for every attribute?
        if isinstance(self.x, str) and bool(self.x):
            return self.x
        else:
            raise RuntimeError("Object is not configured")

    def ready(self) -> bool:
        try:  # Clumsy
            self.x_checked
        except Exception:
            return False
        else:
            return True

    def show(self) -> None:
        print(repr(self.x_checked.split()))

Note that the following is not a workaround, since it's an implicit Optional.

    def __init__(self, x: str = None) -> None:
        self.x = x

Your Environment

  • Mypy version used: 1.5.0 (compiled: yes)
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.10.12

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

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

はじめの一歩

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

調査の方向性

最小限の X の例から始め、リンクされている mypy のディスカッション #4805 と #15207 で提案されているアプローチを比較します。有用な解決策では、メソッド間の narrowing がサポートされているかどうかを明らかにします。サポートされていない場合は、推奨される workaround を文書化するか、必要な動作を追加します。

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

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

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

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