Skip to content

Commit 43308df

Browse files
[2.7] bpo-34974: Do not replace unexpected errors in bytearray(). (GH-9852) (GH-9885)
The bytearray constructor converted unexpected exceptions (e.g. MemoryError and KeyboardInterrupt) to TypeError. (cherry picked from commit e890421)
1 parent 8ba7267 commit 43308df

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

Lib/test/test_bytes.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,8 @@ def test_from_buffer(self):
116116
a = self.type2test(b"\x01\x02\x03")
117117
self.assertEqual(a, b"\x01\x02\x03")
118118

119-
# http://bugs.python.org/issue29159
120-
# Fallback when __index__ raises exception other than OverflowError
119+
# Issues #29159 and #34974.
120+
# Fallback when __index__ raises a TypeError
121121
class B(bytes):
122122
def __index__(self):
123123
raise TypeError
@@ -156,6 +156,20 @@ def test_constructor_value_errors(self):
156156
self.assertRaises(ValueError, self.type2test, [sys.maxint+1])
157157
self.assertRaises(ValueError, self.type2test, [10**100])
158158

159+
def test_constructor_exceptions(self):
160+
# Issue #34974: bytes and bytearray constructors replace unexpected
161+
# exceptions.
162+
class BadInt:
163+
def __index__(self):
164+
1/0
165+
self.assertRaises(ZeroDivisionError, self.type2test, BadInt())
166+
self.assertRaises(ZeroDivisionError, self.type2test, [BadInt()])
167+
168+
class BadIterable:
169+
def __iter__(self):
170+
1/0
171+
self.assertRaises(ZeroDivisionError, self.type2test, BadIterable())
172+
159173
def test_compare(self):
160174
b1 = self.type2test([1, 2, 3])
161175
b2 = self.type2test([1, 2, 3])
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
The :class:`bytearray` constructor no longer convert
2+
unexpected exceptions (e.g. :exc:`MemoryError` and :exc:`KeyboardInterrupt`)
3+
to :exc:`TypeError`.

Objects/bytearrayobject.c

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,10 @@ _getbytevalue(PyObject* arg, int *value)
4141
else {
4242
PyObject *index = PyNumber_Index(arg);
4343
if (index == NULL) {
44-
PyErr_Format(PyExc_TypeError,
45-
"an integer or string of size 1 is required");
44+
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
45+
PyErr_Format(PyExc_TypeError,
46+
"an integer or string of size 1 is required");
47+
}
4648
return 0;
4749
}
4850
face_value = PyLong_AsLong(index);
@@ -852,7 +854,7 @@ bytearray_init(PyByteArrayObject *self, PyObject *args, PyObject *kwds)
852854
/* Is it an int? */
853855
count = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
854856
if (count == -1 && PyErr_Occurred()) {
855-
if (PyErr_ExceptionMatches(PyExc_OverflowError))
857+
if (!PyErr_ExceptionMatches(PyExc_TypeError))
856858
return -1;
857859
PyErr_Clear();
858860
}

0 commit comments

Comments
 (0)