]> granicus.if.org Git - python/commitdiff
Change sys.intern() so that unicode strings can be
authorWalter Dörwald <walter@livinglogic.de>
Tue, 5 Jun 2007 20:22:04 +0000 (20:22 +0000)
committerWalter Dörwald <walter@livinglogic.de>
Tue, 5 Jun 2007 20:22:04 +0000 (20:22 +0000)
interned too. Add a test for this.

Lib/test/test_sys.py
Python/sysmodule.c

index 4118da4abaff61cf6440478beff5e48945138947..8862661e05d2239249bfe104e337f07be92fca37 100644 (file)
@@ -356,7 +356,7 @@ class SysModuleTest(unittest.TestCase):
         # We don't want them in the interned dict and if they aren't
         # actually interned, we don't want to create the appearance
         # that they are by allowing intern() to succeeed.
-        class S(str):
+        class S(str8):
             def __hash__(self):
                 return 123
 
@@ -368,6 +368,17 @@ class SysModuleTest(unittest.TestCase):
         setattr(s, s, s)
         self.assertEqual(getattr(s, s), s)
 
+        s = "never interned as unicode before"
+        self.assert_(sys.intern(s) is s)
+        s2 = s.swapcase().swapcase()
+        self.assert_(sys.intern(s2) is s)
+
+        class U(str):
+            def __hash__(self):
+                return 123
+
+        self.assertRaises(TypeError, sys.intern, U("abc"))
+
 
 def test_main():
     test.test_support.run_unittest(SysModuleTest)
index 17568349d5182277fb56eea81e15140a7aa7e6d5..a8bb918f5aba4685477bd785c9232f9a68c3bc48 100644 (file)
@@ -266,14 +266,21 @@ sys_intern(PyObject *self, PyObject *args)
        PyObject *s;
        if (!PyArg_ParseTuple(args, "S:intern", &s))
                return NULL;
-       if (!PyString_CheckExact(s)) {
-               PyErr_SetString(PyExc_TypeError,
-                               "can't intern subclass of string");
+       if (PyString_CheckExact(s)) {
+               Py_INCREF(s);
+               PyString_InternInPlace(&s);
+               return s;
+       }
+       else if (PyUnicode_CheckExact(s)) {
+               Py_INCREF(s);
+               PyUnicode_InternInPlace(&s);
+               return s;
+       }
+       else {
+               PyErr_Format(PyExc_TypeError,
+                               "can't intern %.400s", s->ob_type->tp_name);
                return NULL;
        }
-       Py_INCREF(s);
-       PyString_InternInPlace(&s);
-       return s;
 }
 
 PyDoc_STRVAR(intern_doc,