[pypy-commit] pypy py3k: Test and fix for allowing __len__ to return any index-like

rlamy pypy.commits at gmail.com
Tue Sep 27 12:42:45 EDT 2016


Author: Ronan Lamy <ronan.lamy at gmail.com>
Branch: py3k
Changeset: r87416:494a05343a22
Date: 2016-09-27 17:42 +0100
http://bitbucket.org/pypy/pypy/changeset/494a05343a22/

Log:	Test and fix for allowing __len__ to return any index-like

diff --git a/pypy/objspace/descroperation.py b/pypy/objspace/descroperation.py
--- a/pypy/objspace/descroperation.py
+++ b/pypy/objspace/descroperation.py
@@ -277,7 +277,7 @@
 
     def _check_len_result(space, w_obj):
         # Will complain if result is too big.
-        result = space.int_w(w_obj, allow_conversion=False)
+        result = space.getindex_w(w_obj, space.w_OverflowError)
         if result < 0:
             raise oefmt(space.w_ValueError, "__len__() should return >= 0")
         return result
diff --git a/pypy/objspace/test/test_descroperation.py b/pypy/objspace/test/test_descroperation.py
--- a/pypy/objspace/test/test_descroperation.py
+++ b/pypy/objspace/test/test_descroperation.py
@@ -293,7 +293,7 @@
             x = operate(A())
             assert x == 'àèì'
             assert type(x) is str
-            
+
 
     def test_byte_results_unicode(self):
         class A(object):
@@ -692,6 +692,34 @@
         raises(TypeError, bool, X(X(2)))
         raises(OverflowError, len, X(sys.maxsize + 1))
 
+    def test_len_index(self):
+        class Index(object):
+            def __index__(self):
+                return 42
+        class X(object):
+            def __len__(self):
+                return Index()
+        n = len(X())
+        assert type(n) is int
+        assert n == 42
+
+        class BadIndex(object):
+            def __index__(self):
+                return 'foo'
+        class Y(object):
+            def __len__(self):
+                return BadIndex()
+        excinfo = raises(TypeError, len, Y())
+        assert excinfo.value.args[0].startswith("__index__ returned non-")
+
+        class BadIndex2(object):
+            def __index__(self):
+                return 2**100
+        class Z(object):
+            def __len__(self):
+                return BadIndex2()
+        excinfo = raises(OverflowError, len, Z())
+
     def test_sane_len(self):
         # this test just tests our assumptions about __len__
         # this will start failing if __len__ changes assertions


More information about the pypy-commit mailing list