diff options
author | Nick Coghlan <ncoghlan@gmail.com> | 2013-11-03 07:00:51 (GMT) |
---|---|---|
committer | Nick Coghlan <ncoghlan@gmail.com> | 2013-11-03 07:00:51 (GMT) |
commit | 8e113b418df7d0c8480e1e2de29a385e1f31b15b (patch) | |
tree | d57fd872f36da8ecfc0626358667550f4e768070 /Lib/contextlib.py | |
parent | 4e641df09b47dd48c26a18b9f2191a8c44ee2c03 (diff) | |
download | cpython-8e113b418df7d0c8480e1e2de29a385e1f31b15b.zip cpython-8e113b418df7d0c8480e1e2de29a385e1f31b15b.tar.gz cpython-8e113b418df7d0c8480e1e2de29a385e1f31b15b.tar.bz2 |
Close #19403: make contextlib.redirect_stdout reentrant
Diffstat (limited to 'Lib/contextlib.py')
-rw-r--r-- | Lib/contextlib.py | 12 |
1 files changed, 4 insertions, 8 deletions
diff --git a/Lib/contextlib.py b/Lib/contextlib.py index fb89118..d3219f6 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -166,20 +166,16 @@ class redirect_stdout: def __init__(self, new_target): self._new_target = new_target - self._old_target = self._sentinel = object() + # We use a list of old targets to make this CM re-entrant + self._old_targets = [] def __enter__(self): - if self._old_target is not self._sentinel: - raise RuntimeError("Cannot reenter {!r}".format(self)) - self._old_target = sys.stdout + self._old_targets.append(sys.stdout) sys.stdout = self._new_target return self._new_target def __exit__(self, exctype, excinst, exctb): - restore_stdout = self._old_target - self._old_target = self._sentinel - sys.stdout = restore_stdout - + sys.stdout = self._old_targets.pop() class suppress: |