Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
bpo-41546: pprint (like print) does not write to stdout when it is None
  • Loading branch information
iritkatriel committed Jul 3, 2021
commit 69741ecc46f368afa90b8578597727bfc2ad2c71
7 changes: 6 additions & 1 deletion Lib/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,13 @@ def __init__(self, indent=1, width=80, depth=None, stream=None, *,
self._width = width
if stream is not None:
self._stream = stream
else:
elif _sys.stdout is not None:
self._stream = _sys.stdout
else:
class _NullStdout:
def write(self, s):
return 0
self._stream = _NullStdout()
Comment thread
iritkatriel marked this conversation as resolved.
Outdated
self._compact = bool(compact)
self._sort_dicts = sort_dicts
self._underscore_numbers = underscore_numbers
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,10 @@ 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):
pprint.pprint('this should not fail')

def test_knotted(self):
# Verify .isrecursive() and .isreadable() w/ recursion
# Tie a knot.
Expand Down Expand Up @@ -241,6 +246,9 @@ def test_same_as_repr(self):
.replace('\n', ' '), native)
self.assertEqual(pprint.pformat(simple, underscore_numbers=True), native)
self.assertEqual(pprint.saferepr(simple), native)
with contextlib.redirect_stdout(None):
# smoke test - there is no output to check
pprint.pprint(simple)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is not it already tested in test_stdout_is_None?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, this is no longer needed, I'll remove. With my first (more complex) solution this covered more code paths.


def test_container_repr_override_called(self):
N = 1000
Expand Down