Skip to content

negative_indices=False seems to be ignored in some cases #2539

@bsolomon1124

Description

@bsolomon1124

From enhancements buffer:

  • negative_indices -- Boolean, defaults to True. If set to False, the buffer will not support the usual wrap-around for negative indices, i.e. all negative indices are out-of-bounds. This can make it more convenient to write code that is optimal when bounds-checking is turned off (i.e. no casting to unsigned ints is necesarry to get optimial access without any if-tests).

It seems like this argument is ignored if using a negative index to access a row of the array:

# bufferstruct.pyx

from cython cimport Py_ssize_t
import numpy as np
from numpy cimport ndarray, float64_t, int64_t
cimport numpy as cnp
cnp.import_array()

def negind_read_one():
    cdef ndarray[dtype=float64_t, ndim=2, negative_indices=False] arr
    arr = np.arange(6, dtype=np.float64).reshape(2, 3)
    return arr[-1]

def negind_read_both():
    cdef ndarray[dtype=float64_t, ndim=2, negative_indices=False] arr
    arr = np.arange(6, dtype=np.float64).reshape(2, 3)
    return arr[-1, -1]

def negind_write():
    cdef ndarray[dtype=float64_t, ndim=2, negative_indices=False] arr
    arr = np.arange(6, dtype=np.float64).reshape(2, 3)
    arr[-1, -1] = np.nan
    return arr

def normal_write():
    cdef ndarray[dtype=float64_t, ndim=2] arr
    arr = np.arange(6, dtype=np.float64).reshape(2, 3)
    arr[-1, -1] = np.nan
    return arr

That is, shouldn't negind_read_one() raise the same IndexError as the rest?

>>> negind_read_one()
array([3., 4., 5.])

>>> negind_read_both()
Traceback (most recent call last):
  File "<ipython-input-4-1dbb30ed3ea9>", line 1, in <module>
    negind_read_both()
  File "bufferstruct.pyx", line 17, in bufferstruct.negind_read_both
    return arr[-1, -1]
IndexError: Out of bounds on buffer access (axis 1)


>>> negind_write()
Traceback (most recent call last):
  File "<ipython-input-5-36ef52623779>", line 1, in <module>
    negind_write()
  File "bufferstruct.pyx", line 22, in bufferstruct.negind_write
    arr[-1, -1] = np.nan
IndexError: Out of bounds on buffer access (axis 1)


>>> normal_write()
array([[ 0.,  1.,  2.],
       [ 3.,  4., nan]])

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions