[Python-checkins] r60893 - in python/trunk: Lib/test/test_unicode.py Objects/stringlib/string_format.h

eric.smith python-checkins at python.org
Mon Feb 18 19:02:35 CET 2008


Author: eric.smith
Date: Mon Feb 18 19:02:34 2008
New Revision: 60893

Modified:
   python/trunk/Lib/test/test_unicode.py
   python/trunk/Objects/stringlib/string_format.h
Log:
Added code to correct combining str and unicode in ''.format().  Added test case.

Modified: python/trunk/Lib/test/test_unicode.py
==============================================================================
--- python/trunk/Lib/test/test_unicode.py	(original)
+++ python/trunk/Lib/test/test_unicode.py	Mon Feb 18 19:02:34 2008
@@ -1088,6 +1088,15 @@
         self.assertRaises(ValueError, format, "", "-")
         self.assertRaises(ValueError, "{0:=s}".format, '')
 
+        # test combining string and unicode
+        self.assertEqual(u"foo{0}".format('bar'), u'foobar')
+        # This will try to convert the argument from unicode to str, which
+        #  will succeed
+        self.assertEqual("foo{0}".format(u'bar'), 'foobar')
+        # This will try to convert the argument from unicode to str, which
+        #  will fail
+        self.assertRaises(UnicodeEncodeError, "foo{0}".format, u'\u1000bar')
+
 def test_main():
     test_support.run_unittest(__name__)
 

Modified: python/trunk/Objects/stringlib/string_format.h
==============================================================================
--- python/trunk/Objects/stringlib/string_format.h	(original)
+++ python/trunk/Objects/stringlib/string_format.h	Mon Feb 18 19:02:34 2008
@@ -493,6 +493,22 @@
     if (result == NULL)
         goto done;
 
+#if PY_VERSION_HEX >= 0x03000000
+    assert(PyString_Check(result));
+#else
+    assert(PyString_Check(result) || PyUnicode_Check(result));
+
+    /* Convert result to our type.  We could be str, and result could
+       be unicode */
+    {
+	PyObject *tmp = STRINGLIB_TOSTR(result);
+	if (tmp == NULL)
+	    goto done;
+	Py_DECREF(result);
+	result = tmp;
+    }
+#endif
+
     ok = output_data(output,
                      STRINGLIB_STR(result), STRINGLIB_LEN(result));
 done:


More information about the Python-checkins mailing list