Skip to content

Remove Dead Code in PyObject_Print #98421

Description

@MonadChains

Bug report

While working on covering PyObject_Print, I noticed that I couldn't hit some lines with any test. Specifically, the part that checks the type of the representation of the object returned by PyObject_Str or PyObject_Repr:

cpython/Objects/object.c

Lines 280 to 308 in f4ead48

PyObject *s;
if (flags & Py_PRINT_RAW)
s = PyObject_Str(op);
else
s = PyObject_Repr(op);
if (s == NULL)
ret = -1;
else if (PyBytes_Check(s)) {
fwrite(PyBytes_AS_STRING(s), 1,
PyBytes_GET_SIZE(s), fp);
}
else if (PyUnicode_Check(s)) {
PyObject *t;
t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
if (t == NULL) {
ret = -1;
}
else {
fwrite(PyBytes_AS_STRING(t), 1,
PyBytes_GET_SIZE(t), fp);
Py_DECREF(t);
}
}
else {
PyErr_Format(PyExc_TypeError,
"str() or repr() returned '%.100s'",
Py_TYPE(s)->tp_name);
ret = -1;
}

As pointed out by @encukou, both aforementioned functions already check and ensure that the return type is a Python string:

cpython/Objects/object.c

Lines 492 to 498 in f4ead48

if (!PyUnicode_Check(res)) {
_PyErr_Format(tstate, PyExc_TypeError,
"__str__ returned non-string (type %.200s)",
Py_TYPE(res)->tp_name);
Py_DECREF(res);
return NULL;
}

cpython/Objects/object.c

Lines 433 to 439 in f4ead48

if (!PyUnicode_Check(res)) {
_PyErr_Format(tstate, PyExc_TypeError,
"__repr__ returned non-string (type %.200s)",
Py_TYPE(res)->tp_name);
Py_DECREF(res);
return NULL;
}

So it is possible to simplify the function by excluding the useless checks of types diffent from Python string.

Activity

  1. removed
    type-bugAn unexpected behavior, bug, or error
    on Oct 19, 2022
  2. mdboom commented on Oct 19, 2022

    @mdboom
    Contributor

    Linking to coverage metabug #94808

  3. added a commit that references this issue on Oct 20, 2022
  4. added a commit that references this issue on Oct 20, 2022
  5. auvipy commented on Oct 20, 2022

    @auvipy

    #98422 was merged, can we close this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions