bpo-41546: make pprint (like print) not write to stdout when it is None by iritkatriel · Pull Request #26810 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 14 additions & 26 deletions Doc/library/pprint.rst
5 changes: 3 additions & 2 deletions Lib/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,9 @@ def __init__(self, indent=1, width=80, depth=None, stream=None, *,
self._underscore_numbers = underscore_numbers

def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
self._stream.write("\n")
if self._stream is not None:
self._format(object, self._stream, 0, 0, {}, 0)
self._stream.write("\n")

def pformat(self, object):
sio = _StringIO()
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_pprint.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-

import collections
import contextlib
import dataclasses
import io
import itertools
Expand Down Expand Up @@ -159,6 +160,13 @@ def test_basic(self):
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))

def test_stdout_is_None(self):
with contextlib.redirect_stdout(None):
# smoke test - there is no output to check
value = 'this should not fail'
pprint.pprint(value)
pprint.PrettyPrinter().pprint(value)

def test_knotted(self):
# Verify .isrecursive() and .isreadable() w/ recursion
# Tie a knot.
Expand Down