From: Tim Peters Date: Tue, 11 Sep 2001 01:41:59 +0000 (+0000) Subject: More on SF bug [#460020] bug or feature: unicode() and subclasses. X-Git-Tag: v2.2.1c1~1868 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=5a49ade70e19a76aa252cd596accf79930765f31;p=python More on SF bug [#460020] bug or feature: unicode() and subclasses. Repaired str(i) to return a genuine string when i is an instance of a str subclass. New PyString_CheckExact() macro. --- diff --git a/Include/stringobject.h b/Include/stringobject.h index a67e33e3a8..052eacf85e 100644 --- a/Include/stringobject.h +++ b/Include/stringobject.h @@ -52,6 +52,7 @@ typedef struct { extern DL_IMPORT(PyTypeObject) PyString_Type; #define PyString_Check(op) PyObject_TypeCheck(op, &PyString_Type) +#define PyString_CheckExact(op) ((op)->ob_type == &PyString_Type) extern DL_IMPORT(PyObject *) PyString_FromStringAndSize(const char *, int); extern DL_IMPORT(PyObject *) PyString_FromString(const char *); diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index d756dc57d0..0de4dec078 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -1440,7 +1440,7 @@ def inherits(): verify(u == s) s = madstring("12345") #XXX verify(str(s) == "12345") - #XXX verify(str(s).__class__ is str) + verify(str(s).__class__ is str) class madunicode(unicode): _rev = None diff --git a/Objects/object.c b/Objects/object.c index 704ffc13b2..718dddf7cf 100644 --- a/Objects/object.c +++ b/Objects/object.c @@ -250,10 +250,16 @@ PyObject_Str(PyObject *v) if (v == NULL) return PyString_FromString(""); - if (PyString_Check(v)) { + if (PyString_CheckExact(v)) { Py_INCREF(v); return v; } + if (PyString_Check(v)) { + /* For a string subtype that's not a string, return a true + string with the same string data. */ + PyStringObject *s = (PyStringObject *)v; + return PyString_FromStringAndSize(s->ob_sval, s->ob_size); + } if (v->ob_type->tp_str == NULL) return PyObject_Repr(v); diff --git a/Objects/stringobject.c b/Objects/stringobject.c index 4c28500962..9c873ecc89 100644 --- a/Objects/stringobject.c +++ b/Objects/stringobject.c @@ -2711,7 +2711,7 @@ str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds) tmp = string_new(&PyString_Type, args, kwds); if (tmp == NULL) return NULL; - assert(PyString_Check(tmp)); + assert(PyString_CheckExact(tmp)); new = type->tp_alloc(type, n = PyString_GET_SIZE(tmp)); if (new != NULL) memcpy(PyString_AS_STRING(new), PyString_AS_STRING(tmp), n+1);