Search code examples
pythonnumpyclassiteratorassign

Class iteration over internal numpy array ? Assignment?


How do you make class to iterate by its internal numpy array : Just idea which does not work :

class ABC:

  def __init__(self):
     self.ary = np.zeros(50)

  def __iter__(self): return np.nditer(self.ary)
  def next(self): ...??..

Also how to make assignment work too :

abc = ABC()
abc[5] = 12
abc[7:9] 0

Solution

  • From documentation,

    iterator.__next__():

    Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.

    For setting and getting values for container class, you need to implement __getitem__ and __setitem__.

    For your sample code

    class ABC():
      def __init__(self):
         self.ary = np.zeros(50)
         self.index = self.ary.shape[0]
    
      def __iter__(self): 
         return np.nditer(self.ary)
    
      def next(self):
          if self.index == 0:
              raise StopIteration
          self.index = self.index - 1
          return self.data[self.index]
    
      def _check_indx(self, idx):
          if abs(idx) >= self.ary.shape[0]:
              raise IndexError(f"Invalid Index {idx} for array with shape {self.ary.shape}")
    
      def __setitem__(self, idx, value):
          self._check_indx(idx)
          self.ary[idx] = value
    
      def __getitem__(self, idx):
          self._check_indx(idx)
          return self.ary[idx]