8000 API: Add and redefine `numpy.bool` [Array API] by mtsokol · Pull Request #25080 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

API: Add and redefine numpy.bool [Array API] #25080

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

Merged
merged 3 commits into from
Nov 24, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Move from np.bool_ to np.bool
  • Loading branch information
mtsokol committed Nov 22, 2023
commit 45f805783fa905a5350acfd33da76c75795a10f0
2 changes: 1 addition & 1 deletion benchmarks/benchmarks/bench_ufunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ def time_divide_scalar2_inplace(self, dtype):

class CustomComparison(Benchmark):
params = (np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16,
np.uint32, np.uint64, np.float32, np.float64, np.bool_)
np.uint32, np.uint64, np.float32, np.float64, np.bool)
param_names = ['dtype']

def setup(self, dtype):
Expand Down
3 changes: 2 additions & 1 deletion doc/release/upcoming_changes/25080.change.rst
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
* Redefine `numpy.bool` as an alias for `numpy.bool_` for Array API compatibility.
* Redefine `numpy.bool` as an alias for `numpy.bool_` (as opposed to the `bool`
it was until NumPy 1.24) for Array API compatibility.
6 changes: 3 additions & 3 deletions doc/source/user/basics.types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ confusion with builtin python type names, such as `numpy.bool_`.
- Actual C type
- Description

* - `numpy.bool_` or `numpy.bool`
* - `numpy.bool` or `numpy.bool_`
- N/A
- ``bool`` (defined in ``stdbool.h``)
- Boolean (True or False) stored as a byte.
Expand Down Expand Up @@ -141,7 +141,7 @@ aliases are provided (See :ref:`sized-aliases`).
NumPy numerical types are instances of ``dtype`` (data-type) objects, each
having unique characteristics. Once you have imported NumPy using
``>>> import numpy as np``
the dtypes are available as ``np.bool_``, ``np.float32``, etc.
the dtypes are available as ``np.bool``, ``np.float32``, etc.

Advanced types, not listed above, are explored in
section :ref:`structured_arrays`.
Expand Down Expand Up @@ -187,7 +187,7 @@ the type itself as a function. For example: ::
array([0, 1, 2], dtype=int8)

Note that, above, we use the *Python* float object as a dtype. NumPy knows
that ``int`` refers to ``np.int_``, ``bool`` means ``np.bool_``,
that ``int`` refers to ``np.int_``, ``bool`` means ``np.bool``,
that ``float`` is ``np.float64`` and ``complex`` is ``np.complex128``.
The other data-types do not have Python equivalents.

Expand Down
5 changes: 1 addition & 4 deletions numpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
array_str, asanyarray, asarray, ascontiguousarray, asfortranarray,
atleast_1d, atleast_2d, atleast_3d, base_repr, binary_repr,
bitwise_and, bitwise_count, bitwise_not, bitwise_or, bitwise_xor,
block, bool_, broadcast, busday_count, busday_offset, busdaycalendar,
block, bool, bool_, broadcast, busday_count, busday_offset, busdaycalendar,
byte, bytes_, can_cast, cbrt, cdouble, ceil, character, choose, clip,
clongdouble, complex128, complex64, complexfloating, compress,
concatenate, conj, conjugate, convolve, copysign, copyto, correlate,
Expand Down Expand Up @@ -284,9 +284,6 @@
# import with `from numpy import *`.
__future_scalars__ = {"str", "bytes", "object"}

# Redefined in NumPy 2.0.
globals()["bool"] = bool_

# now that numpy core module is imported, can initialize limits
_core.getlimits._register_known_types()

Expand Down
408 changes: 204 additions & 204 deletions numpy/__init__.pyi

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions numpy/_core/_dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def _construction_repr(dtype, include_align=False, short=False):
def _scalar_str(dtype, short):
byteorder = _byte_order_str(dtype)

if dtype.type == np.bool_:
if dtype.type == np.bool:
if short:
return "'?'"
else:
Expand Down Expand Up @@ -334,7 +334,7 @@ def _name_includes_bit_suffix(dtype):
if dtype.type == np.object_:
# pointer size varies by system, best to omit it
return False
elif dtype.type == np.bool_:
elif dtype.type == np.bool:
# implied
return False
elif dtype.type is None:
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/_type_aliases.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"single": "float32",
"csingle": "complex64",
"half": "float16",
"bool_": "bool",
# Default integer:
"int_": "intp",
"uint": "uintp",
Expand All @@ -63,7 +64,6 @@
# extra aliases are added only to `sctypeDict`
# to support dtype name access, such as`np.dtype("float")`
_extra_aliases = {
"bool": "bool_",
"float": "float64",
"complex": "complex128",
"object": "object_",
Expand Down
18 changes: 9 additions & 9 deletions numpy/_core/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from .overrides import set_array_function_like_doc, set_module
from .umath import (multiply, invert, sin, PINF, NAN)
from . import numerictypes
from .numerictypes import bool_
from .numerictypes import bool
from ..exceptions import AxisError
from ._ufunc_config import errstate, _no_nep50_warning

Expand Down Expand Up @@ -480,7 +480,7 @@ def count_nonzero(a, axis=None, *, keepdims=False):
if np.issubdtype(a.dtype, np.character):
a_bool = a != a.dtype.type()
else:
a_bool = a.astype(np.bool_, copy=False)
a_bool = a.astype(np.bool, copy=False)

return a_bool.sum(axis=axis, dtype=np.intp, keepdims=keepdims)

Expand Down Expand Up @@ -2250,7 +2250,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):

"""
res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
return bool(res)
return builtins.bool(res)


def _isclose_dispatcher(a, b, rtol=None, atol=None, equal_nan=None):
Expand Down Expand Up @@ -2446,13 +2446,13 @@ def array_equal(a1, a2, equal_nan=False):
if a1.shape != a2.shape:
return False
if not equal_nan:
return bool((a1 == a2).all())
return builtins.bool((a1 == a2).all())
cannot_have_nan = (_dtype_cannot_hold_nan(a1.dtype)
and _dtype_cannot_hold_nan(a2.dtype))
if cannot_have_nan:
if a1 is a2:
return True
return bool((a1 == a2).all())
return builtins.bool((a1 == a2).all())

if a1 is a2:
# nan will compare equal so an array will compare equal to itself.
Expand All @@ -2463,7 +2463,7 @@ def array_equal(a1, a2, equal_nan=False):
if not (a1nan == a2nan).all():
return False
# Shapes of a1, a2 and masks are guaranteed to be consistent by this point
return bool((a1[~a1nan] == a2[~a1nan]).all())
return builtins.bool((a1[~a1nan] == a2[~a1nan]).all())


def _array_equiv_dispatcher(a1, a2):
Expand Down Expand Up @@ -2515,13 +2515,13 @@ def array_equiv(a1, a2):
except Exception:
return False

return bool((a1 == a2).all())
return builtins.bool((a1 == a2).all())


inf = PINF
nan = NAN
False_ = bool_(False)
True_ = bool_(True)
False_ = bool(False)
True_ = bool(True)


def extend_all(module):
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/src/multiarray/arraytypes.h.src
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT int BOOL_argmax,
* CFLOAT, CDOUBLE, CLONGDOUBLE,
* STRING, UNICODE, VOID, OBJECT,
* DATETIME, TIMEDELTA#
* #name = bool_,
* #name = bool,
* 10000 float16, float32, float64, longdouble,
* complex64, complex128, clongdouble,
* bytes_, str_, void, object_,
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/src/multiarray/conversion_utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -989,7 +989,7 @@ PyArray_PyIntAsIntp_ErrMsg(PyObject *o, const char * msg)

/*
* Be a bit stricter and not allow bools.
* np.bool_ is also disallowed as Boolean arrays do not currently
* np.bool is also disallowed as Boolean arrays do not currently
* support index.
*/
if (!o || PyBool_Check(o) || PyArray_IsScalar(o, Bool)) {
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/src/multiarray/scalartypes.c.src
Original file line number Diff line number Diff line change
Expand Up @@ -3398,7 +3398,7 @@ static PyObject *
bool_index(PyObject *a)
{
if (DEPRECATE(
"In future, it will be an error for 'np.bool_' scalars to be "
"In future, it will be an error for 'np.bool' scalars to be "
"interpreted as an index") < 0) {
return NULL;
}
Expand Down
4 changes: 2 additions & 2 deletions numpy/_core/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,8 +310,8 @@ def test_array_astype_warning(t):
assert_warns(np.exceptions.ComplexWarning, a.astype, t)

@pytest.mark.parametrize(["dtype", "out_dtype"],
[(np.bytes_, np.bool_),
(np.str_, np.bool_),
[(np.bytes_, np.bool),
(np.str_, np.bool),
(np.dtype("S10,S9"), np.dtype("?,?")),
# The following also checks unaligned unicode access:
(np.dtype("S7,U9"), np.dtype("?,?"))])
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_array_coercion.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def scalar_instances(times=True, extended_precision=True, user_dtype=True):
# Bool:
# XFAIL: Bool should be added, but has some bad properties when it
# comes to strings, see also gh-9875
# yield param(np.bool_(0), id="bool")
# yield param(np.bool(0), id="bool")

# Integers:
yield param(np.int8(2), id="int8")
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_casting_unittests.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def simple_dtype_instances():
def get_expected_stringlength(dtype):
"""Returns the string length when casting the basic dtypes to strings.
"""
if dtype == np.bool_:
if dtype == np.bool:
return 5
if dtype.kind in "iu":
if dtype.itemsize == 1:
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ def test_datetime_array_find_type(self):

# find "supertype" for non-dates and dates

b = np.bool_(True)
b = np.bool(True)
dm = np.datetime64('1970-01-01', 'M')
d = datetime.date(1970, 1, 1)
dt = datetime.datetime(1970, 1, 1, 12, 30, 40)
Expand Down
22 changes: 11 additions & 11 deletions numpy/_core/tests/test_defchararray.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ def test_count(self):
# assert_array_equal(self.B.count('\0'), [[0, 0], [0, 0], [1, 0]])

def test_endswith(self):
assert_(issubclass(self.A.endswith('').dtype.type, np.bool_))
assert_(issubclass(self.A.endswith('').dtype.type, np.bool))
assert_array_equal(self.A.endswith(' '), [[1, 0], [0, 0], [1, 0]])
assert_array_equal(self.A.endswith('3', 0, 3), [[0, 0], [1, 0], [1, 0]])

Expand All @@ -257,31 +257,31 @@ def fail():
assert_(issubclass(np.char.index('abcba', 'b').dtype.type, np.integer))

def test_isalnum(self):
assert_(issubclass(self.A.isalnum().dtype.type, np.bool_))
assert_(issubclass(self.A.isalnum().dtype.type, np.bool))
assert_array_equal(self.A.isalnum(), [[False, False], [True, True], [False, True]])

def test_isalpha(self):
assert_(issubclass(self.A.isalpha().dtype.type, np.bool_))
assert_(issubclass(self.A.isalpha().dtype.type, np.bool))
assert_array_equal(self.A.isalpha(), [[False, False], [False, True], [False, True]])

def test_isdigit(self):
assert_(issubclass(self.A.isdigit().dtype.type, np.bool_))
assert_(issubclass(self.A.isdigit().dtype.type, np.bool))
assert_array_equal(self.A.isdigit(), [[False, False], [True, False], [False, False]])

def test_islower(self):
assert_(issubclass(self.A.islower().dtype.type, np.bool_))
assert_(issubclass(self.A.islower().dtype.type, np.bool))
assert_array_equal(self.A.islower(), [[True, False], [False, False], [False, False]])

def test_isspace(self):
assert_(issubclass(self.A.isspace().dtype.type, np.bool_))
assert_(issubclass(self.A.isspace().dtype.type, np.bool))
assert_array_equal(self.A.isspace(), [[False, False], [False, False], [False, False]])

def test_istitle(self):
assert_(issubclass(self.A.istitle().dtype.type, np.bool_))
assert_(issubclass(self.A.istitle().dtype.type, np.bool))
assert_array_equal(self.A.istitle(), [[False, False], [False, False], [False, False]])

def test_isupper(self):
assert_(issubclass(self.A.isupper().dtype.type, np.bool_))
assert_(issubclass(self.A.isupper().dtype.type, np.bool))
assert_array_equal(self.A.isupper(), [[False, False], [False, False], [False, True]])

def test_rfind(self):
Expand All @@ -301,7 +301,7 @@ def fail():
assert_(issubclass(np.char.rindex('abcba', 'b').dtype.type, np.integer))

def test_startswith(self):
assert_(issubclass(self.A.startswith('').dtype.type, np.bool_))
assert_(issubclass(self.A.startswith('').dtype.type, np.bool))
assert_array_equal(self.A.startswith(' '), [[1, 0], [0, 0], [0, 0]])
assert_array_equal(self.A.startswith('1', 0, 3), [[0, 0], [1, 0], [1, 0]])

Expand Down Expand Up @@ -570,7 +570,7 @@ def fail():
self.A.isnumeric()

assert_raises(TypeError, fail)
assert_(issubclass(self.B.isnumeric().dtype.type, np.bool_))
assert_(issubclass(self.B.isnumeric().dtype.type, np.bool))
assert_array_equal(self.B.isnumeric(), [
[False, False], [True, False], [False, False]])

Expand All @@ -580,7 +580,7 @@ def fail():
self.A.isdecimal()

assert_raises(TypeError, fail)
assert_(issubclass(self.B.isdecimal().dtype.type, np.bool_))
assert_(issubclass(self.B.isdecimal().dtype.type, np.bool))
assert_array_equal(self.B.isdecimal(), [
[False, False], [True, False], [False, False]])

Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_dlpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def test_from_dlpack_refcount(self):
assert sys.getrefcount(x) == 2

@pytest.mark.parametrize("dtype", [
np.bool_,
np.bool,
np.int8, np.int16, np.int32, np.int64,
np.uint8, np.uint16, np.uint32, np.uint64,
np.float16, np.float32, np.float64,
Expand Down
4 changes: 2 additions & 2 deletions numpy/_core/tests/test_dtype.py
F438
Original file line number Diff line number Diff line change
Expand Up @@ -1434,7 +1434,7 @@ def test_complex_other_value_based(self,
assert res == expected

@pytest.mark.parametrize(["other", "expected"],
[(np.bool_, np.complex128),
[(np.bool, np.complex128),
(np.int64, np.complex128),
(np.float16, np.complex64),
(np.float32, np.complex64),
Expand Down Expand Up @@ -1505,7 +1505,7 @@ def test_float_int_pyscalar_promote_rational(
([1., 1., np.int64], np.float64),
([1., 1j, np.float64], np.complex128),
([1j, 1j, np.float64], np.complex128),
([1, True, np.bool_], np.int_),
([1, True, np.bool], np.int_),
])
def test_permutations_do_not_influence_result(self, dtypes, expected):
# Tests that most permutations do not influence the result. In the
Expand Down
6 changes: 3 additions & 3 deletions numpy/_core/tests/test_einsum.py
Original file line number Diff line number Diff line change
Expand Up @@ -909,10 +909,10 @@ def test_different_paths(self, dtype):
def test_small_boolean_arrays(self):
# See gh-5946.
# Use array of True embedded in False.
a = np.zeros((16, 1, 1), dtype=np.bool_)[:2]
a = np.zeros((16, 1, 1), dtype=np.bool)[:2]
a[...] = True
out = np.zeros((16, 1, 1), dtype=np.bool_)[:2]
tgt = np.ones((2, 1, 1), dtype=np.bool_)
out = np.zeros((16, 1, 1), dtype=np.bool)[:2]
tgt = np.ones((2, 1, 1), dtype=np.bool)
res = np.einsum('...ij,...jk->...ik', a, a, out=out)
assert_equal(res, tgt)

Expand Down
6 changes: 3 additions & 3 deletions numpy/_core/tests/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,8 @@ def test_too_many_fancy_indices_special_case(self):
def test_scalar_array_bool(self):
# NumPy bools can be used as boolean index (python ones as of yet not)
a = np.array(1)
assert_equal(a[np.bool_(True)], a[np.array(True)])
assert_equal(a[np.bool_(False)], a[np.array(False)])
assert_equal(a[np.bool(True)], a[np.array(True)])
assert_equal(a[np.bool(False)], a[np.array(False)])

# After deprecating bools as integers:
#a = np.array([0,1,2])
Expand Down Expand Up @@ -1289,7 +1289,7 @@ def test_bool_as_int_argument_errors(self):
a = np.array([[[1]]])

assert_raises(TypeError, np.reshape, a, (True, -1))
assert_raises(TypeError, np.reshape, a, (np.bool_(True), -1))
assert_raises(TypeError, np.reshape, a, (np.bool(True), -1))
# Note that operator.index(np.array(True)) does not work, a boolean
# array is thus also deprecated, but not with the same message:
assert_raises(TypeError, operator.index, np.array(True))
Expand Down
4 changes: 2 additions & 2 deletions numpy/_core/tests/test_mem_overlap.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@ def check(a, b):
assert_array_equal(c1, c2)

# Trigger "fancy ufunc loop" code path
mask = view_element_first_byte(b).view(np.bool_)
mask = view_element_first_byte(b).view(np.bool)

a[...] = a_orig
b[...] = b_orig
Expand Down Expand Up @@ -876,7 +876,7 @@ def check(a, out, mask):
assert_array_equal(c1, c2)

# Check behavior with same input and output arrays
x = np.arange(100).astype(np.bool_)
x = np.arange(100).astype(np.bool)
check(x, x, x)
check(x, x.copy(), x)
check(x, x, x.copy())
Expand Down
Loading
0