File tree Expand file tree Collapse file tree 3 files changed +24
-6
lines changed Expand file tree Collapse file tree 3 files changed +24
-6
lines changed Original file line number Diff line number Diff line change @@ -770,10 +770,18 @@ class FloatLen:
770
770
def __len__ (self ):
771
771
return 4.5
772
772
self .assertRaises (TypeError , len , FloatLen ())
773
+ class NegativeLen :
774
+ def __len__ (self ):
775
+ return - 10
776
+ self .assertRaises (ValueError , len , NegativeLen ())
773
777
class HugeLen :
774
778
def __len__ (self ):
775
779
return sys .maxsize + 1
776
780
self .assertRaises (OverflowError , len , HugeLen ())
781
+ class HugeNegativeLen :
782
+ def __len__ (self ):
783
+ return - sys .maxsize - 10
784
+ self .assertRaises (ValueError , len , HugeNegativeLen ())
777
785
class NoLenMethod (object ): pass
778
786
self .assertRaises (TypeError , len , NoLenMethod ())
779
787
Original file line number Diff line number Diff line change @@ -10,6 +10,9 @@ What's New in Python 3.7.0 alpha 1?
10
10
Core and Builtins
11
11
-----------------
12
12
13
+ - bpo-29839: len() now raises ValueError rather than OverflowError if
14
+ __len__() returned a large negative integer.
15
+
13
16
- bpo-11913: README.rst is now included in the list of distutils standard
14
17
READMEs and therefore included in source distributions.
15
18
Original file line number Diff line number Diff line change @@ -5924,14 +5924,21 @@ slot_sq_length(PyObject *self)
5924
5924
5925
5925
if (res == NULL )
5926
5926
return -1 ;
5927
- len = PyNumber_AsSsize_t (res , PyExc_OverflowError );
5928
- Py_DECREF (res );
5929
- if (len < 0 ) {
5930
- if (!PyErr_Occurred ())
5931
- PyErr_SetString (PyExc_ValueError ,
5932
- "__len__() should return >= 0" );
5927
+
5928
+ Py_SETREF (res , PyNumber_Index (res ));
5929
+ if (res == NULL )
5930
+ return -1 ;
5931
+
5932
+ assert (PyLong_Check (res ));
5933
+ if (Py_SIZE (res ) < 0 ) {
5934
+ PyErr_SetString (PyExc_ValueError ,
5935
+ "__len__() should return >= 0" );
5933
5936
return -1 ;
5934
5937
}
5938
+
5939
+ len = PyNumber_AsSsize_t (res , PyExc_OverflowError );
5940
+ assert (len >= 0 || PyErr_ExceptionMatches (PyExc_OverflowError ));
5941
+ Py_DECREF (res );
5935
5942
return len ;
5936
5943
}
5937
5944
You can’t perform that action at this time.
0 commit comments