[pypy-svn] r15857 - in pypy/dist/pypy/module/__builtin__: . test

arigo at codespeak.net arigo at codespeak.net
Tue Aug 9 19:22:00 CEST 2005


Author: arigo
Date: Tue Aug  9 19:21:56 2005
New Revision: 15857

Modified:
   pypy/dist/pypy/module/__builtin__/app_functional.py
   pypy/dist/pypy/module/__builtin__/test/test_functional.py
Log:
Oups, sorry:  len(iter(xrange(..)))  works indeed in Python 2.4.
Re-implemented it as a separate xrange_iterator class.



Modified: pypy/dist/pypy/module/__builtin__/app_functional.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/app_functional.py	(original)
+++ pypy/dist/pypy/module/__builtin__/app_functional.py	Tue Aug  9 19:21:56 2005
@@ -310,10 +310,28 @@
         raise IndexError, "xrange object index out of range"
 
     def __iter__(self):
-        i = 0
-        while i < self.len:   
-            yield self.start + i * self.step 
-            i += 1 
+        return xrange_iterator(self.start, self.len, self.step)
+
+
+class xrange_iterator(object):
+    def __init__(self, current, remaining, step):
+        self._current = current
+        self._remaining = remaining
+        self._step = step
+
+    def __iter__(self):
+        return self
+
+    def next(self):
+        if self._remaining > 0:
+            item = self._current
+            self._current = item + self._step
+            self._remaining -= 1
+            return item
+        raise StopIteration
+
+    def __len__(self):
+        return self._remaining
 
 # ____________________________________________________________
 

Modified: pypy/dist/pypy/module/__builtin__/test/test_functional.py
==============================================================================
--- pypy/dist/pypy/module/__builtin__/test/test_functional.py	(original)
+++ pypy/dist/pypy/module/__builtin__/test/test_functional.py	Tue Aug  9 19:21:56 2005
@@ -99,6 +99,22 @@
       # test again, to make sure that xrange() is not its own iterator
       assert list(x) == [2, 5, 8]
 
+   def test_xrange_iter(self):
+      x = xrange(2, 9, 3)
+      it = iter(x)
+      assert iter(it) is it
+      assert len(it) == 3
+      assert it.next() == 2
+      assert len(it) == 2
+      assert it.next() == 5
+      assert len(it) == 1
+      assert it.next() == 8
+      assert len(it) == 0
+      raises(StopIteration, it.next)
+      assert len(it) == 0
+      # test again, to make sure that xrange() is not its own iterator
+      assert iter(x).next() == 2
+
 class AppTestReversed:
    def test_reversed(self):
       r = reversed("hello")



More information about the Pypy-commit mailing list