Skip to content

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

Description

@finite-state-machine

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.

fromtypingimport*@finalclassSomeClass:
def__bool__(self) ->Literal[True]:
returnTrueinstance: SomeClassreveal_type(instance.__bool__()) # 'Literal[True]' - correctreveal_type(bool(instance)) # 'bool' - incorrect (should be 'Literal[True]')ifinstance:
reveal_type(instance) # 'SomeClass' - correctelse:
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions