bpo-41546: make pprint (like print) not write to stdout when it is No… · python/cpython@aab1899 · GitHub
Skip to content

Commit aab1899

Browse files
authored
bpo-41546: make pprint (like print) not write to stdout when it is None (GH-26810)
1 parent 2c20558 commit aab1899

4 files changed

Lines changed: 26 additions & 28 deletions

File tree

Doc/library/pprint.rst

Lines changed: 14 additions & 26 deletions

Lib/pprint.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,8 +148,9 @@ def __init__(self, indent=1, width=80, depth=None, stream=None, *,
148148
self._underscore_numbers = underscore_numbers
149149

150150
def pprint(self, object):
151-
self._format(object, self._stream, 0, 0, {}, 0)
152-
self._stream.write("\n")
151+
if self._stream is not None:
152+
self._format(object, self._stream, 0, 0, {}, 0)
153+
self._stream.write("\n")
153154

154155
def pformat(self, object):
155156
sio = _StringIO()

Lib/test/test_pprint.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22

33
import collections
4+
import contextlib
45
import dataclasses
56
import io
67
import itertools
@@ -159,6 +160,13 @@ def test_basic(self):
159160
self.assertTrue(pp.isreadable(safe),
160161
"expected isreadable for %r" % (safe,))
161162

163+
def test_stdout_is_None(self):
164+
with contextlib.redirect_stdout(None):
165+
# smoke test - there is no output to check
166+
value = 'this should not fail'
167+
pprint.pprint(value)
168+
pprint.PrettyPrinter().pprint(value)
169+
162170
def test_knotted(self):
163171
# Verify .isrecursive() and .isreadable() w/ recursion
164172
# Tie a knot.
Lines changed: 1 addition & 0 deletions

0 commit comments

Comments
 (0)