mirror of
https://github.com/python/cpython.git
synced 2025-08-03 16:39:00 +00:00
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:
parent
d5c43065d5
commit
ad7c98e264
10 changed files with 119 additions and 6 deletions
|
@ -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)
|
||||
{
|
||||
|
|
|
@ -413,6 +413,7 @@ PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
|
|||
}
|
||||
else
|
||||
v = PyUnicode_Decode(s, len, encoding, errors);
|
||||
|
||||
done:
|
||||
if (owned) {
|
||||
Py_DECREF(obj);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue