Index: Objects/unicodeobject.c =================================================================== --- Objects/unicodeobject.c (revision 77197) +++ Objects/unicodeobject.c (working copy) @@ -2959,13 +2959,6 @@ return NULL; } -/* Return a Unicode-Escape string version of the Unicode object. - - If quotes is true, the string is enclosed in u"" or u'' quotes as - appropriate. - -*/ - Py_LOCAL_INLINE(const Py_UNICODE *) findchar(const Py_UNICODE *s, Py_ssize_t size, Py_UNICODE ch) @@ -2981,13 +2974,23 @@ return NULL; } +/* Return a Unicode-Escape string version of the Unicode object. + + If enclose_in_quotes is true, the string is enclosed in u"" or u'' + quotes as appropriate. Otherwise, single quotes are always + escaped. + +*/ + static PyObject *unicodeescape_string(const Py_UNICODE *s, Py_ssize_t size, - int quotes) + int enclose_in_quotes) { PyObject *repr; char *p; + /* non-zero if single quotes should be escaped */ + int escape_single_quotes = 1; static const char *hexdigit = "0123456789abcdef"; #ifdef Py_UNICODE_WIDE @@ -3026,17 +3029,20 @@ p = PyString_AS_STRING(repr); - if (quotes) { + if (enclose_in_quotes) { *p++ = 'u'; - *p++ = (findchar(s, size, '\'') && - !findchar(s, size, '"')) ? '"' : '\''; + if (findchar(s, size, '\'') && !findchar(s, size, '"')) { + *p++ = '"'; + escape_single_quotes = 0; + } else { + *p++ = '\''; + } } while (size-- > 0) { Py_UNICODE ch = *s++; /* Escape quotes and backslashes */ - if ((quotes && - ch == (Py_UNICODE) PyString_AS_STRING(repr)[1]) || ch == '\\') { + if ((escape_single_quotes && ch == '\'') || ch == '\\') { *p++ = '\\'; *p++ = (char) ch; continue; @@ -3121,7 +3127,7 @@ else *p++ = (char) ch; } - if (quotes) + if (enclose_in_quotes) *p++ = PyString_AS_STRING(repr)[1]; *p = '\0';