[Python] Why is contextlib._RedirectStream implemented as a reentrant context manager?

Discussão em 'Python' iniciado por Stack, Junho 16, 2025.

  1. Stack

    Stack Membro Participativo

    While reading the code of the _RedirectStream class from the contextlib module, I couldn't understand the purpose of saving the current stdin, stdout, or stderr file into the _old_targets list:

    class _RedirectStream(AbstractContextManager):


    _stream = None


    def __init__(self, new_target):
    self._new_target = new_target
    # We use a list of old targets to make this CM re-entrant
    self._old_targets = []


    def __enter__(self):
    self._old_targets.append(getattr(sys, self._stream))
    setattr(sys, self._stream, self._new_target)
    return self._new_target


    def __exit__(self, exctype, excinst, exctb):
    setattr(sys, self._stream, self._old_targets.pop())


    The documentation states that the list is used to make the context manager reentrant. But what's the practical benefit of that in the case of redirecting input or output to a file? In what situation would this be needed?

    Continue reading...

Compartilhe esta Página