1

(This question is a copy of https://stackoverflow.com/questions/27693298/how-can-i-handle-python-slice-objects-easily)

The actual use case is the simplest ever: I want to clamp all getitem requests that come in to only refer to a smaller range of the given array (one dimensional example follows):

X
X
X
u
u
u

The array is length 6, but only the first three are "used" -- so I want to restrict slicing to only refer to those three items. It's easy to implement this, but I have the nagging feeling that it's been implemented many many times before, and I'd rather not reinvent the wheel. Searching on Google and here yielded nothing (but maybe I'm not seeing it)...

def absclamp(int x, int maximum):
    if x > maximum:
        return maximum
    elif x > 0:
        return x
    elif x <= -1 * maximum:
        return -1 * maximum
    else:
        return x


class ArrayToHaveContentsCopiedFrom(object):
    def __getitem__(self, thing):
        if isinstance(thing, slice):
            start, stop, step = thing.start, thing.stop, thing.step
            if thing.start is None:
                start = 0
            if thing.stop is None:
                stop = self.size
            if thing.step is None:
                step = 1
            return self.buffer[absclamp(start, self.size): #line wrap here
                absclamp(stop, self.size): absclamp(step, self.size)]
        elif isinstance(thing, int):
            return self.buffer[absclamp(thing, self.size)]
        else:
            raise KeyError("wrong type of index %s"%(thing,))
  • Why not just copy the relevant slice to a new array and discard the old one? – Steve Barnes Dec 29 '14 at 18:53
  • The idea here is that this is a vector that keeps higher locality of reference -- so this data structure is used by other parts of the program, to avoid allocating and freeing all the time. That's why it wants to control access, and make sure that the unused cells don't appear. This question is here because I'm sure other people have done this or similar, and I don't want to reinvent the wheel – Henry Crutcher Dec 29 '14 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.