Skip to content

Require SupportsBool instead of bool for comparisons. #14375

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

randolf-scholz
Copy link
Contributor

Fixes #12562.

Essentially a reopen of #12939 with additional tests. This PR was closed due to a misunderstanding.

Note that an earlier comment by JelleZijlstra suggested that SupportsBool is equivalent to object in practice. This does not seem to quite be the case: Code sample in pyright playground

from typing import Protocol, runtime_checkable

@runtime_checkable
class SupportsBool(Protocol):
    def __bool__(self) -> bool: ...

x: SupportsBool = True
y: SupportsBool = object()  # mypy: ❌ pyright:  ❌

assert isinstance(x, SupportsBool)  # ✅
assert not isinstance(y, SupportsBool)  # ✅

Indeed, despite the documentation mentioning object.__bool__, this method is not defined on object. Rather, the truthiness of an object is defined roughly like:

if hasattr(obj, "__bool__"):
    return obj.__bool__()
if hasattr(obj, "__len__"):
   return bool(len(obj))
return True

This comment has been minimized.

Copy link
Contributor

github-actions bot commented Jul 7, 2025

Diff from mypy_primer, showing the effect of this PR on open source code:

colour (https://github.com/colour-science/colour)
- colour/plotting/colorimetry.py:565: error: Value of type variable "SupportsRichComparisonT" of "min" cannot be "floating[_16Bit] | floating[_32Bit] | float64"  [type-var]
- colour/plotting/colorimetry.py:566: error: Value of type variable "SupportsRichComparisonT" of "max" cannot be "floating[_16Bit] | floating[_32Bit] | float64"  [type-var]

jax (https://github.com/google/jax)
+ jax/_src/pallas/mosaic/pipeline.py:1546: error: Unused "type: ignore" comment  [unused-ignore]

ibis (https://github.com/ibis-project/ibis)
- ibis/expr/types/relations.py:2986: error: Value of type variable "SupportsRichComparisonT" of "sorted" cannot be "NumericValue | float"  [type-var]

arviz (https://github.com/arviz-devs/arviz)
- arviz/stats/ecdf_utils.py:72: error: Value of type variable "SupportsRichComparisonT" of "min" cannot be "Any | float64"  [type-var]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

False positive with builtins.min(T, T) if T.__lt__ doesn't return a builtins.bool
2 participants