Skip to content

Spurious error for code that fails truthy-bool even when not enabled #18026

@huonw

Description

@huonw

Bug Report

It seems that code failing to pass the truthy-bool check can have spurious errors that occur, even when that optional error code isn't enabled.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=53000744586f03d23bb53f807d5a0ea0

class Truthy: 
    pass
    # def __bool__(self) -> bool: return True

def foo(truthies: list[Truthy]) -> None:
    sum(1 if x else 0 for x in truthies)

Expected Behavior

This code should typecheck fine: sum on ints is sensible!

Uncommenting the __bool__ definition (so that the truthy-bool error no longer applies, if it was enabled) passes type checking.

Actual Behavior

main.py:4: error: Generator has incompatible item type "int"; expected "bool"  [misc]

(Note that the truthy-bool error doesn't occur, as expected, because it isn't enabled.)

When running with that enabled one sees:

$ mypy testing.py --enable-error-code=truthy-bool
testing.py:7: error: Generator has incompatible item type "int"; expected "bool"  [misc]
testing.py:7: error: "x" has type "Truthy" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]

Your Environment

  • Mypy version used: 1.12.1
  • Mypy command-line flags: N/A see playground
  • Mypy configuration options from mypy.ini (and other config files): N/A see playground
  • Python version used: 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions