diff -r 6a2de662eeb7 Lib/test/test_long.py --- a/Lib/test/test_long.py Thu Jul 28 17:08:52 2016 +0200 +++ b/Lib/test/test_long.py Thu Jul 28 18:15:05 2016 +0200 @@ -1102,6 +1102,7 @@ self.assertEqual((-1).to_bytes(5, 'big', signed=True), b'\xff\xff\xff\xff\xff') self.assertRaises(OverflowError, (1).to_bytes, 0, 'big') + self.assertRaises(OverflowError, (-1).to_bytes, 0, 'big', signed=True) def test_from_bytes(self): def check(tests, byteorder, signed=False): diff -r 6a2de662eeb7 Objects/longobject.c --- a/Objects/longobject.c Thu Jul 28 17:08:52 2016 +0200 +++ b/Objects/longobject.c Thu Jul 28 18:15:05 2016 +0200 @@ -5121,6 +5121,12 @@ return NULL; } + /* Corner case: (-1).to_bytes(0, ...) should raise OverflowError. */ + if (length == 0 && Py_SIZE(v) == -1) { + PyErr_SetString(PyExc_OverflowError, "int too big to convert"); + return NULL; + } + bytes = PyBytes_FromStringAndSize(NULL, length); if (bytes == NULL) return NULL;