Skip to content

np.bool_ and bool are incompatible #10385

@mlondschien

Description

@mlondschien

Bug Report

From numpy/numpy#18876:

Reproducing code example:

# example.py
import numpy as np

def f(x: bool) -> bool:
    return x

y = np.bool_(True)

print(f(y))

yields

$ mypy example.py
example.py:9: error: Argument 1 to "f" has incompatible type "bool_"; expected "bool"
Found 1 error in 1 file (checked 1 source file)

The same happens for the inverse:

# example.py
import numpy as np

def f(x: np.bool_) -> np.bool_:
    return x

y = True

print(f(y))

results in

example.py:9: error: Argument 1 to "f" has incompatible type "bool"; expected "bool_"

np.float_ and np.int_ work fine.

As @BvB93 points out, this is not an issue that numpy can fix, as python does not allow creating subclasses of bool:

Runtime:

In [1]: class bool_(bool): pass
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-823896cfc52c> in <module>
----> 1 class bool_(bool): pass

TypeError: type 'bool' is not an acceptable base type

mypy:

In [2]: from typing import TYPE_CHECKING

In [3]: if TYPE_CHECKING:
   ...:     class bool_(bool): pass  # error: 'bool' is not a valid base class
   ...:

Is there a possibility to fix this within mypy? E.g. by adding a new Bool or BoolLike type that allows for comparisons. numpy could then possibly create np.bool_ as a subclass of Bool.

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