(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,))