Skip to content

Commit cd49a51

Browse files
committed
Use PyObject_Pretty to implement the print(pretty=True) case
1 parent 62a1c04 commit cd49a51

File tree

1 file changed

+10
-25
lines changed

1 file changed

+10
-25
lines changed

Python/bltinmodule.c

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2341,30 +2341,10 @@ builtin_print_impl(PyObject *module, PyObject * const *objects,
23412341
return NULL;
23422342
}
23432343
if (pretty == Py_True) {
2344-
/* Use default `pprint.PrettyPrinter` */
2345-
PyObject *printer_factory = PyImport_ImportModuleAttrString("pprint", "PrettyPrinter");
2346-
PyObject *printer_instance = NULL;
2347-
2348-
if (!printer_factory) {
2349-
Py_DECREF(file);
2350-
return NULL;
2351-
}
2352-
2353-
printer_instance = PyObject_CallNoArgs(printer_factory);
2354-
Py_DECREF(printer_factory);
2355-
2356-
if (!printer_instance) {
2357-
Py_DECREF(file);
2358-
return NULL;
2359-
}
2360-
2361-
printer = PyObject_GetAttrString(printer_instance, "pformat");
2362-
Py_DECREF(printer_instance);
2363-
2364-
if (!printer) {
2365-
Py_DECREF(file);
2366-
return NULL;
2367-
}
2344+
/* Set a marker for the the loop below to use PyObject_Pretty(). Even though Py_True is
2345+
immortal, we increment the reference count to make the loop logic below easier. */
2346+
printer = Py_True;
2347+
Py_INCREF(printer);
23682348
}
23692349
else if (pretty == Py_None) {
23702350
/* Don't use a pretty printer */
@@ -2391,7 +2371,12 @@ builtin_print_impl(PyObject *module, PyObject * const *objects,
23912371
}
23922372

23932373
if (printer) {
2394-
PyObject *prettified = PyObject_CallOneArg(printer, objects[i]);
2374+
/* We're using Py_True as a sentinel to mean "use the default pretty printer". See above for
2375+
the reference counting rationale. */
2376+
PyObject *prettified = (
2377+
printer == Py_True
2378+
? PyObject_Pretty(objects[i])
2379+
: PyObject_CallOneArg(printer, objects[i]));
23952380

23962381
if (!prettified) {
23972382
Py_DECREF(file);

0 commit comments

Comments
 (0)