Support mixed sync and async context managers in `async with` statements
Ninguém assumiu esta issue ainda.
- Linguagem predominante
- Python
- Estrelas
- 77.2k
- Forks
- 35.9k
- Métricas de merge de PRs
- Métricas de PR pendentes
Descrição
Over the last few years, I've found myself writing a lot of code which leans heavily on context managers, and parenthesized context managers make it quite conventient to do so - in all but one case. If you have mixed synchronous and async context managers, each switch from sync to async costs another level of indentation, making the code noticably harder to read.
I therefore propose that the async with statement should also accept mixed sync and async context managers, so long as there is at least one async context manager.
I've been using a helper function which gets most of the way towards this. I nonetheless think that the feature would be valuable, because:
- It guides people away from a "convert to async cm" pattern (e.g.
as_acm(sync_cm()) as v,), which changes code semantics by adding checkpoints where the async framework can switch tasks - and entering or exiting context managers is an unusally bad time to do that, since they are often responsible for timeouts or error handling. - Keeping the
asclauses local helps to avoid naming confusion: when adding or deleting code, it's easy to mismatchasync with multicontext(some(), contexts()) as (a, b):relative toasync with some() as b, contexts as a:. As seen here, it's also more concise.
from contextlib import AsyncExitStack, asynccontextmanager
@asynccontextmanager
async def multicontext(*cms):
assert any(hasattr(cm, "__aenter__") for cm in cms)
async with AsyncExitStack() as stack:
enter, aenter = stack.enter_context, stack.enter_async_context
yield tuple(
(enter(cm) if hasattr(cm, "__enter__") else await aenter(cm))
for cm in cms
)
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere.
Update: now on discuss.python.org to collect feedback.
Guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Direção de pesquisa
Nenhum arquivo-fonte ou teste é mencionado na issue. Comece lendo a proposta e a thread vinculada no discuss.python.org; em seguida, identifique a semântica da linguagem e o escopo de implementação necessários para permitir gerenciadores de contexto síncronos e assíncronos mistos. O trabalho estará concluído quando a sintaxe e o comportamento estiverem acordados e cobertos por testes apropriados.
Escrita pelo modelo de indexação a partir do texto da issue.
Avaliação
- Stack de tecnologia
- python
- Domínio
- compilers
- Tipo de issue
- Funcionalidade
- Dificuldade
- 5/5
- Tempo estimado
- Mais de uma semana
- Status de atividade
- Estagnada
- Clareza
- Razoavelmente clara
- Facilidade para iniciantes
- 35/100