title: When subclassing a numpy ndarray, how can I modify __getitem__ properly?
body: <p>I am attempting to subclass numpy's ndarray. In my subclass, called <code>MyClass</code>, I've added a field called <code>time</code> as a parallel array to the main data.</p>
  
  <p>My goal is the following: suppose I make an instance of MyClass, let's call it <code>mc</code>.
  I slice <code>mc</code>, for instance <code>mc[2:6]</code>, and I want the resulting object to contain not only the properly sliced np array, but also the correspondingly sliced <code>time</code> array.</p>
  
  <p>Here is my attempt:</p>
  
  <pre><code>class MyClass(np.ndarray):
      def __new__(cls, data, time=None):
          obj = np.asarray(data).view(cls)
          obj.time = time
          return obj
      def __array_finalize__(self, obj):
          setattr(self, 'time', obj.time)
      def __getitem__(self, item):
          #print item #for testing
          ret = super(MyClass, self).__getitem__(item)
          ret.time = self.time.__getitem__(item)
          return ret
  </code></pre>
  
  <p>This does not work. After many hours of messing around, I realized it is because when I call <code>mc[2:6]</code>, <code>__getitem__</code> is actually called multiple times. First when it is called, the <code>item</code> variable, as expected, is <code>slice(2,6,None)</code>. But then, the line containing <code>super(MyClass, self)...</code> calls this same function again, presumably to go retrieve the individual elements of the slice.</p>
  
  <p>The issue is that it supplies <code>__getitem__</code> with a strange set of parameters, always negative numbers. In the example of <code>mc[2:6]</code>, it calls the method 4 more times, with <code>item</code> values of -4, -3, -2, and -1.</p>
  
  <p>As you can see, this makes it impossible for me to properly adjust the <code>ret.time</code> variable, since it attempts to modify it multiple times, often with nonsensical indices.</p>
  
  <p>I have tried working around this in many ways, including copying the object and editing that copy instead, taking various views of the object, and many other hacks, but none seem to overcome this issue that <code>__getitem__</code> is repeatedly called with negative indices that do not line up with the requested slice.</p>
  
  <p>Any help or explanations as to what is going on would be greatly appreciated.</p>