0

I want to convert a __getitem__ method from python to accept arrays from cython. I should allow slicing in the second index in this particular application. For python I could write:

class name:
    def __init__(self):
        self.numbers = np.random.rand(2,3) 

    # ...
    # ...

    def __getitem__(self, tup):
        if type(tup) == tuple:
            x, y = tup
            return self.numbers[x][y]
        return self.numbers[tup]

and everything would work great. However, the interpreter doesn't like it when I declare the variable numbers to be the type cdef public double[:,:] numbers and try to call the __getitem__-method with y being a slice-object. Whenever that happens it complains TypeError: 'slice' object cannot be interpreted as an integer. My question is then: How would I modify the line return self.bounds[x][y] such that y is correctly understood in case it's a slice instead of an integer?

Mikkel Rev
  • 863
  • 3
  • 12
  • 31
  • Does this answer your question? [Implementing slicing in \_\_getitem\_\_](https://stackoverflow.com/questions/2936863/implementing-slicing-in-getitem) – wwii May 03 '20 at 22:32
  • @wwii Thanks for your reply. It doesn't seem like it. My question is basically how to give the memoryview array the arguments of the slice object in the most elegant way. – Mikkel Rev May 03 '20 at 23:15
  • Related:? [Cython - Memoryview of a dynamic 2D C++Array](https://stackoverflow.com/questions/53902999/cython-memoryview-of-a-dynamic-2d-carray) – wwii May 04 '20 at 03:19
  • 1
    Would it make sense just to store the data as a generic Python object (e.g. you can convert a typed memory view to a Numpy array with `np.asarray`). Typed memoryviews are really designed for speeding up indexing single elements in a loop in Cython - if that isn't what you're doing then maybe don't use them? – DavidW May 04 '20 at 06:50

0 Answers0