[Python-checkins] bpo-35384: The repr of ctypes.CArgObject no longer fails for non-ascii character. (GH-10863)

Serhiy Storchaka webhook-mailer at python.org
Thu Dec 6 04:16:30 EST 2018


https://github.com/python/cpython/commit/3ffa8b9ba190101f674a0e524e482a83ed09cccd
commit: 3ffa8b9ba190101f674a0e524e482a83ed09cccd
branch: master
author: Serhiy Storchaka <storchaka at gmail.com>
committer: GitHub <noreply at github.com>
date: 2018-12-06T11:16:24+02:00
summary:

bpo-35384: The repr of ctypes.CArgObject no longer fails for non-ascii character. (GH-10863)

files:
M Lib/ctypes/test/test_bytes.py
M Modules/_ctypes/callproc.c

diff --git a/Lib/ctypes/test/test_bytes.py b/Lib/ctypes/test/test_bytes.py
index 20fa05650340..092ec5af0524 100644
--- a/Lib/ctypes/test/test_bytes.py
+++ b/Lib/ctypes/test/test_bytes.py
@@ -12,6 +12,7 @@ def test_c_char(self):
             x.value = "y"
         c_char.from_param(b"x")
         self.assertRaises(TypeError, c_char.from_param, "x")
+        self.assertIn('xbd', repr(c_char.from_param(b"\xbd")))
         (c_char * 3)(b"a", b"b", b"c")
         self.assertRaises(TypeError, c_char * 3, "a", "b", "c")
 
diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c
index 1185c9156ae9..a7965c19b70c 100644
--- a/Modules/_ctypes/callproc.c
+++ b/Modules/_ctypes/callproc.c
@@ -455,6 +455,12 @@ PyCArg_dealloc(PyCArgObject *self)
     PyObject_Del(self);
 }
 
+static int
+is_literal_char(unsigned char c)
+{
+    return c < 128 && _PyUnicode_IsPrintable(c) && c != '\\' && c != '\'';
+}
+
 static PyObject *
 PyCArg_repr(PyCArgObject *self)
 {
@@ -501,8 +507,14 @@ PyCArg_repr(PyCArgObject *self)
         break;
 
     case 'c':
-        sprintf(buffer, "<cparam '%c' (%c)>",
-            self->tag, self->value.c);
+        if (is_literal_char((unsigned char)self->value.c)) {
+            sprintf(buffer, "<cparam '%c' ('%c')>",
+                self->tag, self->value.c);
+        }
+        else {
+            sprintf(buffer, "<cparam '%c' ('\\x%02x')>",
+                self->tag, (unsigned char)self->value.c);
+        }
         break;
 
 /* Hm, are these 'z' and 'Z' codes useful at all?
@@ -517,8 +529,14 @@ PyCArg_repr(PyCArgObject *self)
         break;
 
     default:
-        sprintf(buffer, "<cparam '%c' at %p>",
-            self->tag, self);
+        if (is_literal_char((unsigned char)self->tag)) {
+            sprintf(buffer, "<cparam '%c' at %p>",
+                (unsigned char)self->tag, self);
+        }
+        else {
+            sprintf(buffer, "<cparam 0x%02x at %p>",
+                (unsigned char)self->tag, self);
+        }
         break;
     }
     return PyUnicode_FromString(buffer);



More information about the Python-checkins mailing list