Skip to content

Commit 69741ec

Browse files
committed
bpo-41546: pprint (like print) does not write to stdout when it is None
1 parent bc39614 commit 69741ec

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

Lib/pprint.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,13 @@ def __init__(self, indent=1, width=80, depth=None, stream=None, *,
141141
self._width = width
142142
if stream is not None:
143143
self._stream = stream
144-
else:
144+
elif _sys.stdout is not None:
145145
self._stream = _sys.stdout
146+
else:
147+
class _NullStdout:
148+
def write(self, s):
149+
return 0
150+
self._stream = _NullStdout()
146151
self._compact = bool(compact)
147152
self._sort_dicts = sort_dicts
148153
self._underscore_numbers = underscore_numbers

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,10 @@ 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+
pprint.pprint('this should not fail')
166+
162167
def test_knotted(self):
163168
# Verify .isrecursive() and .isreadable() w/ recursion
164169
# Tie a knot.
@@ -241,6 +246,9 @@ def test_same_as_repr(self):
241246
.replace('\n', ' '), native)
242247
self.assertEqual(pprint.pformat(simple, underscore_numbers=True), native)
243248
self.assertEqual(pprint.saferepr(simple), native)
249+
with contextlib.redirect_stdout(None):
250+
# smoke test - there is no output to check
251+
pprint.pprint(simple)
244252

245253
def test_container_repr_override_called(self):
246254
N = 1000

0 commit comments

Comments
 (0)