]> granicus.if.org Git - python/commitdiff
Issue #7267: format(int, 'c') now raises OverflowError when the argument is not
authorVictor Stinner <victor.stinner@gmail.com>
Mon, 9 Nov 2015 11:21:09 +0000 (12:21 +0100)
committerVictor Stinner <victor.stinner@gmail.com>
Mon, 9 Nov 2015 11:21:09 +0000 (12:21 +0100)
in range(0, 256).

Lib/test/test_str.py
Misc/NEWS
Objects/stringlib/formatter.h

index 2cd79665580f5d0d05706e11efb57e30c494529d..774c6346ffb0833910c33d839622909a4ca6d0e9 100644 (file)
@@ -428,6 +428,11 @@ class StrTest(
         self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
         self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
 
+    def test_format_c_overflow(self):
+        # issue #7267
+        self.assertRaises(OverflowError, '{0:c}'.format, -1)
+        self.assertRaises(OverflowError, '{0:c}'.format, 256)
+
     def test_buffer_is_readonly(self):
         self.assertRaises(TypeError, sys.stdin.readinto, b"")
 
index f9163d6123298585aef7ce440561325b7d86235f..3ea5c6b99ae609b1af607c517d7b67556c6eacca 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,9 @@ What's New in Python 2.7.11?
 Core and Builtins
 -----------------
 
+- Issue #7267: format(int, 'c') now raises OverflowError when the argument is
+  not in range(0, 256).
+
 - Issue #24806: Prevent builtin types that are not allowed to be subclassed from
   being subclassed through multiple inheritance.
 
index 122abe6c83cdadccf993f550b5c3b8edba96d25b..b75755ef577b0001271095ea6524d3dd0907fd2c 100644 (file)
@@ -789,6 +789,7 @@ format_int_or_long_internal(PyObject *value, const InternalFormatSpec *format,
         x = PyLong_AsLong(value);
         if (x == -1 && PyErr_Occurred())
             goto done;
+#if STRINGLIB_IS_UNICODE
 #ifdef Py_UNICODE_WIDE
         if (x < 0 || x > 0x10ffff) {
             PyErr_SetString(PyExc_OverflowError,
@@ -803,6 +804,13 @@ format_int_or_long_internal(PyObject *value, const InternalFormatSpec *format,
                             "(narrow Python build)");
             goto done;
         }
+#endif
+#else
+        if (x < 0 || x > 0xff) {
+            PyErr_SetString(PyExc_OverflowError,
+                            "%c arg not in range(0x100)");
+            goto done;
+        }
 #endif
         numeric_char = (STRINGLIB_CHAR)x;
         pnumeric_chars = &numeric_char;