contextlib — Utilitários para contextos da instrução with

Código-fonte: Lib/contextlib.py


Este módulo fornece utilitários para tarefas comuns envolvendo a instrução with. Para mais informações, veja também Tipos de Gerenciador de Contexto e Gerenciadores de contexto da instrução with.

Utilitários

Funções e classes fornecidas:

class contextlib.AbstractContextManager

Uma classe base abstrata para classes que implementam object.__enter__() e object.__exit__(). Uma implementação padrão para object.__enter__() é fornecida, que retorna self, enquanto object.__exit__() é um método abstrato que, por padrão, retorna None. Veja também a definição de Tipos de Gerenciador de Contexto.

Adicionado na versão 3.6.

class contextlib.AbstractAsyncContextManager

Uma classe base abstrata para classes que implementam object.__aenter__() e object.__aexit__(). Uma implementação padrão para object.__aenter__() é fornecida, que retorna self, enquanto object.__aexit__() é um método abstrato que, por padrão, retorna None. Veja também a definição de Gerenciadores de contexto assíncronos

Adicionado na versão 3.7.

@contextlib.contextmanager

Esta função é um decorador que pode ser usado para definir uma função de fábrica para gerenciadores de contexto de instrução with, sem precisar criar uma classe ou separar os métodos __enter__() e __exit__().

Embora muitos objetos ofereçam suporte nativo ao uso em instruções with, às vezes é necessário gerenciar um recurso que não seja um gerenciador de contexto por si só e não implemente um método close() para uso com contextlib.closing

Um exemplo abstrato seria o seguinte para garantir o gerenciamento correto dos recursos:

from contextlib import contextmanager

@contextmanager
def managed_resource(*args, **kwds):
    # Códigopara obter recursos como, por exemplo:
    resource = acquire_resource(*args, **kwds)
    try:
        yield resource
    finally:
        # Código para liberar recursos como, por exemplo:
        release_resource(resource)

A função pode, então, ser usada da seguinte forma:

>>> with managed_resource(timeout=3600) as resource:
...     # O recurso é liberado no final deste bloco,
...     # mesmo que o código no bloco levante uma exceção

A função que está sendo decorada deve retornar um iterador gerador quando chamada. Este iterador deve produzir exatamente um valor, que será vinculado aos alvos na cláusula as da instrução with, se houver.

No ponto em que o gerador é produzido, o bloco aninhado na instrução with é executado. O gerador é então retomado após o bloco ser encerrado. Se uma exceção não tratada ocorrer no bloco, ela será levantada novamente dentro do gerador no ponto em que a produção ocorreu. Assim, você pode usar uma instrução tryexceptfinally para capturar o erro (se houver), ou garantir que alguma limpeza ocorra. Se uma exceção for capturada apenas para registrá-la ou para executar alguma ação (em vez de suprimi-la completamente), o gerador deve levantar novamente essa exceção. Caso contrário, o gerenciador de contexto do gerador indicará à instrução with que a exceção foi tratada, e a execução será retomada com a instrução imediatamente após a instrução with.

contextmanager() usa ContextDecorator para que os gerenciadores de contexto que ela cria possam ser usados ​​como decoradores, bem como em instruções with. Quando usada como um decorador, uma nova instância do gerador é implicitamente criada em cada chamada de função (isso permite que os gerenciadores de contexto criados por contextmanager() atendam ao requisito de que os gerenciadores de contexto ofereçam suporte a múltiplas invocações para serem usados ​​como decoradores).

Alterado na versão 3.2: Uso de ContextDecorator.

@contextlib.asynccontextmanager

Semelhante a contextmanager(), mas cria um gerenciador de contexto assíncrono.

Esta função é um decorador que pode ser usado para definir uma função de fábrica para gerenciadores de contexto assíncronos de instrução async with, sem precisar criar uma classe ou separar os métodos __aenter__() e __aexit__(). Ela deve ser aplicada a uma função que atua como gerador assíncrono.

Um exemplo simples:

from contextlib import asynccontextmanager

@asynccontextmanager
async def get_connection():
    conn = await acquire_db_connection()
    try:
        yield conn
    finally:
        await release_db_connection(conn)

async def get_all_users():
    async with get_connection() as conn:
        return conn.query('SELECT ...')

Adicionado na versão 3.7.

Gerenciadores de contexto definidos com asynccontextmanager() podem ser usados ​​como decoradores ou com instruções async with:

import time
from contextlib import asynccontextmanager

@asynccontextmanager
async def timeit():
    now = time.monotonic()
    try:
        yield
    finally:
        print(f'it took {time.monotonic() - now}s to run')

@timeit()
async def main():
    # ... código do async ...

Quando usada como um decorador, uma nova instância do gerador é implicitamente criada em cada chamada de função. Isso permite que os gerenciadores de contexto criados por asynccontextmanager() atendam ao requisito de que os gerenciadores de contexto ofereçam suporte a múltiplas invocações para serem usados ​​como decoradores.

Alterado na versão 3.10: Gerenciadores de contexto assíncronos criados com asynccontextmanager() podem ser usados ​​como decoradores.

contextlib.closing(thing)

Retorna um gerenciador de contexto que fecha thing após a conclusão do bloco. Isso basicamente equivale a:

from contextlib import contextmanager

@contextmanager
def closing(thing):
    try:
        yield thing
    finally:
        thing.close()

E permite que você escreva código como isso:

from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('https://www.python.org')) as page:
    for line in page:
        print(line)

sem precisar fechar explicitamente page. Mesmo se ocorrer um erro, page.close() será chamado quando o bloco with for encerrado.

Nota

A maioria dos tipos que gerenciam recursos suporta o protocolo de gerenciador de contexto, que fecha thing ao sair da declaração with. Como tal, closing() é mais útil para tipos de terceiros que não oferecem suporte a gerenciadores de contexto. Este exemplo é puramente para fins ilustrativos, pois urlopen() normalmente seria usado em um gerenciador de contexto.

contextlib.aclosing(thing)

Retorna um gerenciador de contexto async que chama o método aclose() de thing após a conclusão do bloco. Isso basicamente equivale a:

from contextlib import asynccontextmanager

@asynccontextmanager
async def aclosing(thing):
    try:
        yield thing
    finally:
        await thing.aclose()

De forma significativa, aclosing() oferece suporte a limpeza determinística de geradores assíncronos quando eles são encerrados mais cedo por break ou uma exceção. Por exemplo:

from contextlib import aclosing

async with aclosing(my_generator()) as values:
    async for value in values:
        if value == 42:
            break

Esse padrão garante que o código de saída assíncrono do gerador seja executado no mesmo contexto que suas iterações (para que exceções e variáveis ​​de contexto funcionem conforme o esperado, e o código de saída não seja executado após o tempo de vida de alguma tarefa da qual ele depende).

Adicionado na versão 3.10.

contextlib.nullcontext(enter_result=None)

Retorna um gerenciador de contexto que retorna enter_result de __enter__, mas não faz nada de outra forma. Ele foi criado para ser usado como um substituto para um gerenciador de contexto opcional, por exemplo:

def myfunction(arg, ignore_exceptions=False):
    if ignore_exceptions:
        # Usa suppress para ignorar todas as exceções.
        cm = contextlib.suppress(Exception)
    else:
        # Não ignora quaisquer exceções, cm não tem efeito.
        cm = contextlib.nullcontext()
    with cm:
        # Faz algo

Um exemplo usando enter_result:

def process_file(file_or_path):
    if isinstance(file_or_path, str):
        # Se for uma string, abre o arquivo
        cm = open(file_or_path)
    else:
        # O chamador é responsável por fechar o arquivo
        cm = nullcontext(file_or_path)

    with cm as file:
        # Efetua um processamento no arquivo

Também pode ser usado como um substituto para gerenciadores de contexto assíncronos:

async def send_http(session=None):
    if not session:
        # Se houver nenhuma sessão http, cria-a com aiohttp
        cm = aiohttp.ClientSession()
    else:
        # O chamador é responsável por fechar a sessão
        cm = nullcontext(session)

    async with cm as session:
        # Envia requisições http com sessão

Adicionado na versão 3.7.

Alterado na versão 3.10: Suporte a gerenciador de contexto assíncrono foi adicionado.

contextlib.suppress(*exceptions)

Retorna um gerenciador de contexto que suprime qualquer uma das exceções especificadas se elas ocorrerem no corpo de uma instrução with e então retoma a execução com a primeira instrução após o final da instrução with.

Como qualquer outro mecanismo que suprime completamente exceções, este gerenciador de contexto deve ser usado apenas para cobrir erros muito específicos, onde continuar silenciosamente com a execução do programa é considerado a coisa certa a fazer.

Por exemplo:

from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove('algumarquivo.tmp')

with suppress(FileNotFoundError):
    os.remove('outroarquivo.tmp')

Este código equivale a:

try:
    os.remove('algumarquivo.tmp')
except FileNotFoundError:
    pass

try:
    os.remove('outroarquivo.tmp')
except FileNotFoundError:
    pass

O gerenciador de contexto é reentrante.

Se o código dentro do bloco with levantar uma exceção BaseExceptionGroup, exceções suprimidas são removidas do grupo. Quaisquer exceções do grupo que não forem suprimidas são levantadas novamente em um novo grupo que é criado usando o método derive() do grupo original.

Adicionado na versão 3.4.

Alterado na versão 3.12: suppress now supports suppressing exceptions raised as part of a BaseExceptionGroup.

contextlib.redirect_stdout(new_target)

Context manager for temporarily redirecting sys.stdout to another file or file-like object.

This tool adds flexibility to existing functions or classes whose output is hardwired to stdout.

For example, the output of help() normally is sent to sys.stdout. You can capture that output in a string by redirecting the output to an io.StringIO object. The replacement stream is returned from the __enter__ method and so is available as the target of the with statement:

with redirect_stdout(io.StringIO()) as f:
    help(pow)
s = f.getvalue()

To send the output of help() to a file on disk, redirect the output to a regular file:

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)

To send the output of help() to sys.stderr:

with redirect_stdout(sys.stderr):
    help(pow)

Note that the global side effect on sys.stdout means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts.

O gerenciador de contexto é reentrante.

Adicionado na versão 3.4.

contextlib.redirect_stderr(new_target)

Similar to redirect_stdout() but redirecting sys.stderr to another file or file-like object.

O gerenciador de contexto é reentrante.

Adicionado na versão 3.5.

contextlib.chdir(path)

Non parallel-safe context manager to change the current working directory. As this changes a global state, the working directory, it is not suitable for use in most threaded or async contexts. It is also not suitable for most non-linear code execution, like generators, where the program execution is temporarily relinquished – unless explicitly desired, you should not yield when this context manager is active.

This is a simple wrapper around chdir(), it changes the current working directory upon entering and restores the old one on exit.

O gerenciador de contexto é reentrante.

Adicionado na versão 3.11.

class contextlib.ContextDecorator

A base class that enables a context manager to also be used as a decorator.

Context managers inheriting from ContextDecorator have to implement __enter__ and __exit__ as normal. __exit__ retains its optional exception handling even when used as a decorator.

ContextDecorator is used by contextmanager(), so you get this functionality automatically.

Example of ContextDecorator:

from contextlib import ContextDecorator

class mycontext(ContextDecorator):
    def __enter__(self):
        print('Starting')
        return self

    def __exit__(self, *exc):
        print('Finishing')
        return False

The class can then be used like this:

>>> @mycontext()
... def function():
...     print('The bit in the middle')
...
>>> function()
Starting
The bit in the middle
Finishing

>>> with mycontext():
...     print('The bit in the middle')
...
Starting
The bit in the middle
Finishing

This change is just syntactic sugar for any construct of the following form:

def f():
    with cm():
        # Do stuff

ContextDecorator lets you instead write:

@cm()
def f():
    # Do stuff

It makes it clear that the cm applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too).

Existing context managers that already have a base class can be extended by using ContextDecorator as a mixin class:

from contextlib import ContextDecorator

class mycontext(ContextBaseClass, ContextDecorator):
    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False

Nota

As the decorated function must be able to be called multiple times, the underlying context manager must support use in multiple with statements. If this is not the case, then the original construct with the explicit with statement inside the function should be used.

Adicionado na versão 3.2.

class contextlib.AsyncContextDecorator

Similar to ContextDecorator but only for asynchronous functions.

Example of AsyncContextDecorator:

from asyncio import run
from contextlib import AsyncContextDecorator

class mycontext(AsyncContextDecorator):
    async def __aenter__(self):
        print('Starting')
        return self

    async def __aexit__(self, *exc):
        print('Finishing')
        return False

The class can then be used like this:

>>> @mycontext()
... async def function():
...     print('The bit in the middle')
...
>>> run(function())
Starting
The bit in the middle
Finishing

>>> async def function():
...    async with mycontext():
...         print('The bit in the middle')
...
>>> run(function())
Starting
The bit in the middle
Finishing

Adicionado na versão 3.10.

class contextlib.ExitStack

A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data.

For example, a set of files may easily be handled in a single with statement as follows:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

The __enter__() method returns the ExitStack instance, and performs no additional operations.

Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a with statement). Note that callbacks are not invoked implicitly when the context stack instance is garbage collected.

This stack model is used so that context managers that acquire their resources in their __init__ method (such as file objects) can be handled correctly.

Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested with statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state.

This is a relatively low level API that takes care of the details of correctly unwinding the stack of exit callbacks. It provides a suitable foundation for higher level context managers that manipulate the exit stack in application specific ways.

Adicionado na versão 3.3.

enter_context(cm)

Enters a new context manager and adds its __exit__() method to the callback stack. The return value is the result of the context manager’s own __enter__() method.

These context managers may suppress exceptions just as they normally would if used directly as part of a with statement.

Alterado na versão 3.11: Raises TypeError instead of AttributeError if cm is not a context manager.

push(exit)

Adds a context manager’s __exit__() method to the callback stack.

As __enter__ is not invoked, this method can be used to cover part of an __enter__() implementation with a context manager’s own __exit__() method.

If passed an object that is not a context manager, this method assumes it is a callback with the same signature as a context manager’s __exit__() method and adds it directly to the callback stack.

By returning true values, these callbacks can suppress exceptions the same way context manager __exit__() methods can.

The passed in object is returned from the function, allowing this method to be used as a function decorator.

callback(callback, /, *args, **kwds)

Accepts an arbitrary callback function and arguments and adds it to the callback stack.

Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details).

The passed in callback is returned from the function, allowing this method to be used as a function decorator.

pop_all()

Transfers the callback stack to a fresh ExitStack instance and returns it. No callbacks are invoked by this operation - instead, they will now be invoked when the new stack is closed (either explicitly or implicitly at the end of a with statement).

For example, a group of files can be opened as an “all or nothing” operation as follows:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Hold onto the close method, but don't call it yet.
    close_files = stack.pop_all().close
    # If opening any file fails, all previously opened files will be
    # closed automatically. If all files are opened successfully,
    # they will remain open even after the with statement ends.
    # close_files() can then be invoked explicitly to close them all.
close()

Immediately unwinds the callback stack, invoking callbacks in the reverse order of registration. For any context managers and exit callbacks registered, the arguments passed in will indicate that no exception occurred.

class contextlib.AsyncExitStack

An asynchronous context manager, similar to ExitStack, that supports combining both synchronous and asynchronous context managers, as well as having coroutines for cleanup logic.

The close() method is not implemented; aclose() must be used instead.

coroutine enter_async_context(cm)

Similar to ExitStack.enter_context() but expects an asynchronous context manager.

Alterado na versão 3.11: Raises TypeError instead of AttributeError if cm is not an asynchronous context manager.

push_async_exit(exit)

Similar to ExitStack.push() but expects either an asynchronous context manager or a coroutine function.

push_async_callback(callback, /, *args, **kwds)

Similar to ExitStack.callback() but expects a coroutine function.

coroutine aclose()

Similar to ExitStack.close() but properly handles awaitables.

Continuing the example for asynccontextmanager():

async with AsyncExitStack() as stack:
    connections = [await stack.enter_async_context(get_connection())
        for i in range(5)]
    # All opened connections will automatically be released at the end of
    # the async with statement, even if attempts to open a connection
    # later in the list raise an exception.

Adicionado na versão 3.7.

Exemplos e receitas

This section describes some examples and recipes for making effective use of the tools provided by contextlib.

Supporting a variable number of context managers

The primary use case for ExitStack is the one given in the class documentation: supporting a variable number of context managers and other cleanup operations in a single with statement. The variability may come from the number of context managers needed being driven by user input (such as opening a user specified collection of files), or from some of the context managers being optional:

with ExitStack() as stack:
    for resource in resources:
        stack.enter_context(resource)
    if need_special_resource():
        special = acquire_special_resource()
        stack.callback(release_special_resource, special)
    # Perform operations that use the acquired resources

As shown, ExitStack also makes it quite easy to use with statements to manage arbitrary resources that don’t natively support the context management protocol.

Catching exceptions from __enter__ methods

It is occasionally desirable to catch exceptions from an __enter__ method implementation, without inadvertently catching exceptions from the with statement body or the context manager’s __exit__ method. By using ExitStack the steps in the context management protocol can be separated slightly in order to allow this:

stack = ExitStack()
try:
    x = stack.enter_context(cm)
except Exception:
    # handle __enter__ exception
else:
    with stack:
        # Handle normal case

Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with try/except/finally statements, but not all APIs are well designed in that regard. When a context manager is the only resource management API provided, then ExitStack can make it easier to handle various situations that can’t be handled directly in a with statement.

Cleaning up in an __enter__ implementation

As noted in the documentation of ExitStack.push(), this method can be useful in cleaning up an already allocated resource if later steps in the __enter__() implementation fail.

Here’s an example of doing this for a context manager that accepts resource acquisition and release functions, along with an optional validation function, and maps them to the context management protocol:

from contextlib import contextmanager, AbstractContextManager, ExitStack

class ResourceManager(AbstractContextManager):

    def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
        self.acquire_resource = acquire_resource
        self.release_resource = release_resource
        if check_resource_ok is None:
            def check_resource_ok(resource):
                return True
        self.check_resource_ok = check_resource_ok

    @contextmanager
    def _cleanup_on_error(self):
        with ExitStack() as stack:
            stack.push(self)
            yield
            # The validation check passed and didn't raise an exception
            # Accordingly, we want to keep the resource, and pass it
            # back to our caller
            stack.pop_all()

    def __enter__(self):
        resource = self.acquire_resource()
        with self._cleanup_on_error():
            if not self.check_resource_ok(resource):
                msg = "Failed validation for {!r}"
                raise RuntimeError(msg.format(resource))
        return resource

    def __exit__(self, *exc_details):
        # We don't need to duplicate any of our resource release logic
        self.release_resource()

Replacing any use of try-finally and flag variables

A pattern you will sometimes see is a try-finally statement with a flag variable to indicate whether or not the body of the finally clause should be executed. In its simplest form (that can’t already be handled just by using an except clause instead), it looks something like this:

cleanup_needed = True
try:
    result = perform_operation()
    if result:
        cleanup_needed = False
finally:
    if cleanup_needed:
        cleanup_resources()

As with any try statement based code, this can cause problems for development and review, because the setup code and the cleanup code can end up being separated by arbitrarily long sections of code.

ExitStack makes it possible to instead register a callback for execution at the end of a with statement, and then later decide to skip executing that callback:

from contextlib import ExitStack

with ExitStack() as stack:
    stack.callback(cleanup_resources)
    result = perform_operation()
    if result:
        stack.pop_all()

This allows the intended cleanup behaviour to be made explicit up front, rather than requiring a separate flag variable.

If a particular application uses this pattern a lot, it can be simplified even further by means of a small helper class:

from contextlib import ExitStack

class Callback(ExitStack):
    def __init__(self, callback, /, *args, **kwds):
        super().__init__()
        self.callback(callback, *args, **kwds)

    def cancel(self):
        self.pop_all()

with Callback(cleanup_resources) as cb:
    result = perform_operation()
    if result:
        cb.cancel()

If the resource cleanup isn’t already neatly bundled into a standalone function, then it is still possible to use the decorator form of ExitStack.callback() to declare the resource cleanup in advance:

from contextlib import ExitStack

with ExitStack() as stack:
    @stack.callback
    def cleanup_resources():
        ...
    result = perform_operation()
    if result:
        stack.pop_all()

Devido à maneira como o protocolo decorador funciona, uma função de retorno de chamada declarada dessa forma não pode receber nenhum parâmetro. Em vez disso, quaisquer recursos a serem liberados devem ser acessados ​como variáveis ​de clausura.

Using a context manager as a function decorator

ContextDecorator makes it possible to use a context manager in both an ordinary with statement and also as a function decorator.

For example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, inheriting from ContextDecorator provides both capabilities in a single definition:

from contextlib import ContextDecorator
import logging

logging.basicConfig(level=logging.INFO)

class track_entry_and_exit(ContextDecorator):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        logging.info('Entering: %s', self.name)

    def __exit__(self, exc_type, exc, exc_tb):
        logging.info('Exiting: %s', self.name)

Instances of this class can be used as both a context manager:

with track_entry_and_exit('widget loader'):
    print('Some time consuming activity goes here')
    load_widget()

And also as a function decorator:

@track_entry_and_exit('widget loader')
def activity():
    print('Some time consuming activity goes here')
    load_widget()

Note that there is one additional limitation when using context managers as function decorators: there’s no way to access the return value of __enter__(). If that value is needed, then it is still necessary to use an explicit with statement.

Ver também

PEP 343 - A instrução “with”

A especificação, o histórico e os exemplos para a instrução Python with.

Single use, reusable and reentrant context managers

Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.

This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used (as shown in all of the usage examples above).

Files are an example of effectively single use context managers, since the first with statement will close the file, preventing any further IO operations using that file object.

Context managers created using contextmanager() are also single use context managers, and will complain about the underlying generator failing to yield if an attempt is made to use them a second time:

>>> from contextlib import contextmanager
>>> @contextmanager
... def singleuse():
...     print("Before")
...     yield
...     print("After")
...
>>> cm = singleuse()
>>> with cm:
...     pass
...
Before
After
>>> with cm:
...     pass
...
Traceback (most recent call last):
    ...
RuntimeError: generator didn't yield

Reentrant context managers

More sophisticated context managers may be “reentrant”. These context managers can not only be used in multiple with statements, but may also be used inside a with statement that is already using the same context manager.

threading.RLock is an example of a reentrant context manager, as are suppress(), redirect_stdout(), and chdir(). Here’s a very simple example of reentrant use:

>>> from contextlib import redirect_stdout
>>> from io import StringIO
>>> stream = StringIO()
>>> write_to_stream = redirect_stdout(stream)
>>> with write_to_stream:
...     print("This is written to the stream rather than stdout")
...     with write_to_stream:
...         print("This is also written to the stream")
...
>>> print("This is written directly to stdout")
This is written directly to stdout
>>> print(stream.getvalue())
This is written to the stream rather than stdout
This is also written to the stream

Real world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example.

Note also that being reentrant is not the same thing as being thread safe. redirect_stdout(), for example, is definitely not thread safe, as it makes a global modification to the system state by binding sys.stdout to a different stream.

Gerenciadores de contexto reutilizáveis

Distinct from both single use and reentrant context managers are “reusable” context managers (or, to be completely explicit, “reusable, but not reentrant” context managers, since reentrant context managers are also reusable). These context managers support being used multiple times, but will fail (or otherwise not work correctly) if the specific context manager instance has already been used in a containing with statement.

threading.Lock is an example of a reusable, but not reentrant, context manager (for a reentrant lock, it is necessary to use threading.RLock instead).

Another example of a reusable, but not reentrant, context manager is ExitStack, as it invokes all currently registered callbacks when leaving any with statement, regardless of where those callbacks were added:

>>> from contextlib import ExitStack
>>> stack = ExitStack()
>>> with stack:
...     stack.callback(print, "Callback: from first context")
...     print("Leaving first context")
...
Leaving first context
Callback: from first context
>>> with stack:
...     stack.callback(print, "Callback: from second context")
...     print("Leaving second context")
...
Leaving second context
Callback: from second context
>>> with stack:
...     stack.callback(print, "Callback: from outer context")
...     with stack:
...         stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Callback: from outer context
Leaving outer context

As the output from the example shows, reusing a single stack object across multiple with statements works correctly, but attempting to nest them will cause the stack to be cleared at the end of the innermost with statement, which is unlikely to be desirable behaviour.

Using separate ExitStack instances instead of reusing a single instance avoids that problem:

>>> from contextlib import ExitStack
>>> with ExitStack() as outer_stack:
...     outer_stack.callback(print, "Callback: from outer context")
...     with ExitStack() as inner_stack:
...         inner_stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Leaving outer context
Callback: from outer context