This patch adds a new builtin unistr() which behaves like str()

except that it always returns Unicode objects.

A new C API PyObject_Unicode() is also provided.

This closes patch #101664.

Written by Marc-Andre Lemburg. Copyright assigned to Guido van Rossum.
This commit is contained in:
Marc-André Lemburg 2001-01-17 17:09:53 +00:00
parent d5c43065d5
commit ad7c98e264
10 changed files with 119 additions and 6 deletions

View file

@ -568,6 +568,53 @@ get_inprogress_dict(void)
return inprogress;
}
PyObject *
PyObject_Unicode(PyObject *v)
{
PyObject *res;
if (v == NULL)
res = PyString_FromString("<NULL>");
else if (PyUnicode_Check(v)) {
Py_INCREF(v);
return v;
}
else if (PyString_Check(v))
res = v;
else if (v->ob_type->tp_str != NULL)
res = (*v->ob_type->tp_str)(v);
else {
PyObject *func;
static PyObject *strstr;
if (strstr == NULL) {
strstr= PyString_InternFromString("__str__");
if (strstr == NULL)
return NULL;
}
if (!PyInstance_Check(v) ||
(func = PyObject_GetAttr(v, strstr)) == NULL) {
PyErr_Clear();
res = PyObject_Repr(v);
}
else {
res = PyEval_CallObject(func, (PyObject *)NULL);
Py_DECREF(func);
}
}
if (res == NULL)
return NULL;
if (!PyUnicode_Check(res)) {
PyObject* str;
str = PyUnicode_FromObject(res);
Py_DECREF(res);
if (str)
res = str;
else
return NULL;
}
return res;
}
static PyObject *
make_pair(PyObject *v, PyObject *w)
{

View file

@ -413,6 +413,7 @@ PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
}
else
v = PyUnicode_Decode(s, len, encoding, errors);
done:
if (owned) {
Py_DECREF(obj);