Commits

Amaury Forgeot d'Arc committed 8666c3c

Add array.__iter__ (don't rely on the default behavior with __getitem__),
to make arrays instances of collections.Iterable.

Comments (0)

Files changed (2)

pypy/module/array/interp_array.py

 from pypy.interpreter.buffer import RWBuffer
 from pypy.interpreter.error import OperationError
 from pypy.interpreter.gateway import interp2app, unwrap_spec
-from pypy.interpreter.typedef import GetSetProperty, make_weakref_descr
+from pypy.interpreter.typedef import GetSetProperty, make_weakref_descr, TypeDef
+from pypy.interpreter.baseobjspace import Wrappable
 from pypy.objspace.std.model import W_Object
 from pypy.objspace.std.multimethod import FailedToImplement
 from pypy.objspace.std.stdtypedef import SMM, StdTypeDef
     def get_raw_address(self):
         return self.array._charbuf_start()
 
+
+class ArrayIterator(Wrappable):
+    def __init__(self, array):
+        self.index = 0
+        self.array = array
+        
+    def next_w(self, space):
+        if self.index < self.array.len:
+            w_value = self.array.w_getitem(space, self.index)
+            self.index += 1
+            return w_value
+        raise OperationError(space.w_StopIteration, space.w_None)
+
+ArrayIterator.typedef = TypeDef(
+    'arrayiterator',
+    __next__ = interp2app(ArrayIterator.next_w),
+    )
+
+
 def make_array(mytype):
     W_ArrayBase = globals()['W_ArrayBase']
 
         return _cmp_impl(space, self, other, space.ge)
 
     # Misc methods
+    def iter__Array(space, self):
+        return space.wrap(ArrayIterator(self))
 
     def buffer__Array(space, self):
         return space.wrap(ArrayBuffer(self))

pypy/module/array/test/test_array.py

             assert type(self.array(t)) is self.array
             assert isinstance(self.array(t), self.array)
 
+    def test_iterable(self):
+        import collections
+        for t in 'bBhHiIlLfdu':
+            assert isinstance(self.array(t), collections.Iterable)
+
     def test_subclass(self):
         assert len(self.array('b')) == 0