Skip to content

Commit e192d0b

Browse files
committed
Issue #7267: format(int, 'c') now raises OverflowError when the argument is not
in range(0, 256).
1 parent 8d0a94d commit e192d0b

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

Lib/test/test_str.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,11 @@ def __format__(self, spec):
428428
self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
429429
self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
430430

431+
def test_format_c_overflow(self):
432+
# issue #7267
433+
self.assertRaises(OverflowError, '{0:c}'.format, -1)
434+
self.assertRaises(OverflowError, '{0:c}'.format, 256)
435+
431436
def test_buffer_is_readonly(self):
432437
self.assertRaises(TypeError, sys.stdin.readinto, b"")
433438

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ What's New in Python 2.7.11?
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #7267: format(int, 'c') now raises OverflowError when the argument is
14+
not in range(0, 256).
15+
1316
- Issue #24806: Prevent builtin types that are not allowed to be subclassed from
1417
being subclassed through multiple inheritance.
1518

Objects/stringlib/formatter.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,7 @@ format_int_or_long_internal(PyObject *value, const InternalFormatSpec *format,
789789
x = PyLong_AsLong(value);
790790
if (x == -1 && PyErr_Occurred())
791791
goto done;
792+
#if STRINGLIB_IS_UNICODE
792793
#ifdef Py_UNICODE_WIDE
793794
if (x < 0 || x > 0x10ffff) {
794795
PyErr_SetString(PyExc_OverflowError,
@@ -803,6 +804,13 @@ format_int_or_long_internal(PyObject *value, const InternalFormatSpec *format,
803804
"(narrow Python build)");
804805
goto done;
805806
}
807+
#endif
808+
#else
809+
if (x < 0 || x > 0xff) {
810+
PyErr_SetString(PyExc_OverflowError,
811+
"%c arg not in range(0x100)");
812+
goto done;
813+
}
806814
#endif
807815
numeric_char = (STRINGLIB_CHAR)x;
808816
pnumeric_chars = &numeric_char;

0 commit comments

Comments
 (0)