[Python] contextlib.contextmanager does not raise exceptions if return is in finally clause

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

  1. Stack

    Stack Membro Participativo

    I just encountered a really strange behaviour of python's contextlib.contextmanager. Can anyone explain to me if this is intended (and why):


    If you put a return into the finally of the contextmanager, any exception raised within the contextmanager is no longer raised.
    ​

    from contextlib import contextmanager

    @contextmanager
    def test():
    try:
    print("inside the contextmanager")
    yield
    finally:
    print("exiting contextmanager")
    return # This shomehow shadows any exception raised within the contextmanager

    with test():
    try:
    raise RuntimeError("ASDF")
    except Exception as ex:
    print(f"there's an {ex} exception... lets raise it again!")
    raise ex
    print("i don't care about exceptions")


    If I run this, I get the following:

    >>> inside the contextmanager
    >>> there's an ASDF exception... lets raise it again!
    >>> exiting contextmanager
    >>> i don't care about exceptions


    I would have expected that the exception is raised.

    Continue reading...

Compartilhe esta Página