Skip to content

Commit a60167d

Browse files
author
gvanrossum
committed
Printing objects to a real file still wasn't done right: if the
object's type didn't define tp_print, there were still cases where the full "print uses str() which falls back to repr()" semantics weren't honored. This resulted in >>> print None <None object at 0x80bd674> >>> print type(u'') <type object at 0x80c0a80> Fixed this by always using the appropriate PyObject_Repr() or PyObject_Str() call, rather than trying to emulate what they would do. Also simplified PyObject_Str() to always fall back on PyObject_Repr() when tp_str is not defined (rather than making an extra check for instances with a __str__ method). And got rid of the special case for strings. git-svn-id: http://svn.python.org/projects/python/trunk@20566 6015fed2-1504-0410-9fe1-9d1591cc4771
1 parent f71e223 commit a60167d

1 file changed

Lines changed: 14 additions & 32 deletions

File tree

Objects/object.c

Lines changed: 14 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -196,27 +196,17 @@ PyObject_Print(PyObject *op, FILE *fp, int flags)
196196
fprintf(fp, "<refcnt %u at %p>",
197197
op->ob_refcnt, op);
198198
else if (op->ob_type->tp_print == NULL) {
199-
if ((flags & Py_PRINT_RAW)
200-
? (op->ob_type->tp_str == NULL)
201-
: (op->ob_type->tp_repr == NULL))
202-
{
203-
fprintf(fp, "<%s object at %p>",
204-
op->ob_type->tp_name, op);
205-
}
199+
PyObject *s;
200+
if (flags & Py_PRINT_RAW)
201+
s = PyObject_Str(op);
202+
else
203+
s = PyObject_Repr(op);
204+
if (s == NULL)
205+
ret = -1;
206206
else {
207-
PyObject *s;
208-
if (flags & Py_PRINT_RAW)
209-
s = PyObject_Str(op);
210-
else
211-
s = PyObject_Repr(op);
212-
if (s == NULL)
213-
ret = -1;
214-
else {
215-
ret = PyObject_Print(s, fp,
216-
Py_PRINT_RAW);
217-
}
218-
Py_XDECREF(s);
207+
ret = PyObject_Print(s, fp, Py_PRINT_RAW);
219208
}
209+
Py_XDECREF(s);
220210
}
221211
else
222212
ret = (*op->ob_type->tp_print)(op, fp, flags);
@@ -301,22 +291,14 @@ PyObject_Str(PyObject *v)
301291

302292
if (v == NULL)
303293
return PyString_FromString("<NULL>");
304-
else if (PyString_Check(v)) {
294+
if (PyString_Check(v)) {
305295
Py_INCREF(v);
306296
return v;
307297
}
308-
else if (v->ob_type->tp_str != NULL)
309-
res = (*v->ob_type->tp_str)(v);
310-
else {
311-
PyObject *func;
312-
if (!PyInstance_Check(v) ||
313-
(func = PyObject_GetAttrString(v, "__str__")) == NULL) {
314-
PyErr_Clear();
315-
return PyObject_Repr(v);
316-
}
317-
res = PyEval_CallObject(func, (PyObject *)NULL);
318-
Py_DECREF(func);
319-
}
298+
if (v->ob_type->tp_str == NULL)
299+
return PyObject_Repr(v);
300+
301+
res = (*v->ob_type->tp_str)(v);
320302
if (res == NULL)
321303
return NULL;
322304
if (PyUnicode_Check(res)) {

0 commit comments

Comments
 (0)