Skip to content

Commit eb88192

Browse files
committed
Update reference implementation
For `print(..., pretty=object)` simplify so that it's not an object that has a .pformat() method, but it just needs to be a callable taking a single arg, returning the pretty formatted string.
1 parent 04a776b commit eb88192

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

Lib/test/test_print.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,9 @@ class PPrintable:
205205
def __pprint__(self):
206206
yield 'I feel pretty'
207207

208+
def __str__(self):
209+
return 'Pretty, pretty, pretty good'
210+
208211

209212
class PrettySmart(PrettyPrinter):
210213
def pformat(self, obj):
@@ -232,11 +235,15 @@ def test_pprint_magic(self):
232235
self.assertEqual(self.file.getvalue(), "'one' PPrintable('I feel pretty') 2\n")
233236

234237
def test_custom_pprinter(self):
235-
print('one', PPrintable(), 2, file=self.file, pretty=PrettySmart())
238+
print('one', PPrintable(), 2, file=self.file, pretty=PrettySmart().pformat)
236239
self.assertEqual(self.file.getvalue(), "one PPrintable('I feel pretty') 2\n")
237240

241+
def test_callable_pprinter(self):
242+
print('one', PPrintable(), 2, file=self.file, pretty=str)
243+
self.assertEqual(self.file.getvalue(), "one Pretty, pretty, pretty good 2\n")
244+
238245
def test_bad_pprinter(self):
239-
with self.assertRaises(AttributeError):
246+
with self.assertRaises(TypeError):
240247
print('one', PPrintable(), 2, file=self.file, pretty=object())
241248

242249
def test_fstring(self):

Python/bltinmodule.c

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2343,14 +2343,24 @@ builtin_print_impl(PyObject *module, PyObject * const *objects,
23432343
if (pretty == Py_True) {
23442344
/* Use default `pprint.PrettyPrinter` */
23452345
PyObject *printer_factory = PyImport_ImportModuleAttrString("pprint", "PrettyPrinter");
2346+
PyObject *printer_instance = NULL;
23462347

23472348
if (!printer_factory) {
23482349
Py_DECREF(file);
23492350
return NULL;
23502351
}
2351-
printer = PyObject_CallNoArgs(printer_factory);
2352+
2353+
printer_instance = PyObject_CallNoArgs(printer_factory);
23522354
Py_DECREF(printer_factory);
23532355

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+
23542364
if (!printer) {
23552365
Py_DECREF(file);
23562366
return NULL;
@@ -2381,7 +2391,7 @@ builtin_print_impl(PyObject *module, PyObject * const *objects,
23812391
}
23822392

23832393
if (printer) {
2384-
PyObject *prettified = PyObject_CallMethod(printer, "pformat", "O", objects[i]);
2394+
PyObject *prettified = PyObject_CallOneArg(printer, objects[i]);
23852395

23862396
if (!prettified) {
23872397
Py_DECREF(file);

0 commit comments

Comments
 (0)