[Numpy-discussion] Use of booleans in slices

Aaron Meurer asmeurer at gmail.com
Thu Aug 13 17:14:42 EDT 2020


I noticed that np.bool_.__index__() gives a DeprecationWarning

>>> np.bool_(True).__index__()
__main__:1: DeprecationWarning: In future, it will be an error for
'np.bool_' scalars to be interpreted as an index
1

This is good, because booleans don't actually act like integers in
indexing contexts. However, raw Python bools also allow __index__()

>>> True.__index__()
1

A consequence of this is that NumPy slices allow booleans, as long as
they are the Python type (if you use the NumPy bool_ type you get the
deprecation warning).

>>> a = np.arange(10)
>>> a[True:]
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Should this behavior also be considered deprecated? Presumably
deprecating bool.__index__() in Python is a no-go, but it could be
deprecated in NumPy contexts (in the pure Python collections, booleans
don't have a special indexing meaning anyway).

Interestingly, places that use a shape don't allow booleans (I guess
they don't necessarily use __index__()?)

>>> np.empty((True,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

Aaron Meurer


More information about the NumPy-Discussion mailing list