[Python] Shorter way to define contextmanager by decorator?

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    When creating a decorator using @contextlib.contextmanager(), we have to write

    enter_action(...)
    try:
    yield ...
    finally:
    exit_action(...)


    That is 3 lines just for the (rather unaesthetic) try/yield/finally construct. Why can't we get something like this instead?

    enter_action(...)
    with context_magic(...): # equivalent to try/yield/finally
    exit_action(...)


    Would that be technically possible?

    Continue reading...

Compartilhe esta Página