python / python/mypy

bool(obj) does not infer from obj.__bool__()

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

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

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

説明

Bug Report

(Although there are other issues that allude to this problem, I haven't been able to locate an issue which specifically addresses truthiness where __bool__() is defined and @final. The search term "truthy bool" may be helpful for finding related issues.)

Implicit truthiness does not (always?) take an object's __bool__() into account, even when that method is @final.

To Reproduce

This example is posted to mypy-play.net.

from typing import *

@final
class SomeClass:
    def __bool__(self) -> Literal[True]:
        return True

instance: SomeClass

reveal_type(instance.__bool__())    # 'Literal[True]' - correct
reveal_type(bool(instance))         # 'bool' - incorrect (should be 'Literal[True]')

if instance:
    reveal_type(instance)           # 'SomeClass' - correct
else:
    assert_never(instance)          # ...'SomeClass' - incorrect (should be silent)

(Whether the class or method is decorated @final makes no difference.)

Expected Behavior

if instance: ... and bool(instnace) should take into account that SomeClass has a @final __bool__() with return type Literal[True], and consistently treat instances of SomeClass as definitely truthy.

In general, implicit truthiness for an object should take into account the truthiness of the return type of any @final __bool__() the object's class defines.

Comments inline in the above code highlight differences from expected behaviour.

Actual Behavior

main.py:10: note: Revealed type is "Literal[True]"
main.py:11: note: Revealed type is "builtins.bool"
main.py:14: note: Revealed type is "__main__.SomeClass"
main.py:16: error: Argument 1 to "assert_never" has incompatible type "SomeClass"; expected "NoReturn"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.4.0, master (2023-06-26)
  • Mypy command-line flags: (none)
  • Mypy configuration options from mypy.ini (and other config files): (none)
  • Python version used: 3.11

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

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

はじめの一歩

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

調査の方向性

issue の main.py 再現コードから始め、instance.bool()、bool(instance)、および if 文での truthiness narrowing の処理を比較します。関連する型推論と narrowing のエントリーポイントを追跡し、その後 Literal[True] を返す final bool() のカバレッジを追加します。bool(instance) が Literal[True] を明らかにし、到達不能な else 分岐で assert_never エラーが発生しなくなれば完了です。

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

評価

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

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

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