This rule raises an issue when a @contextmanager or @asynccontextmanager generator performs cleanup after yield without guaranteeing that cleanup still runs if the generator exits early.

This rule raises no issue in test code.

This rule raises no issue when every except re-raises, and either the enclosing with binds a name used after yield or an except BaseException cleans up before re-raising.

A catch-all except around yield that does not re-raise is an issue too when it sits inside a with or async with of the same generator. That context manager then exits as if nothing failed and skips the cleanup it runs on failure.

from contextlib import contextmanager

@contextmanager
def transactional(connection):
    transaction = connection.begin()
    try:
        yield connection
        transaction.commit()
    except BaseException:  # Compliant: rollback runs, then the error is re-raised
        transaction.rollback()
        raise
from contextlib import contextmanager

@contextmanager
def traced(tracer, name):
    with tracer.start_as_current_span(name) as span:
        try:
            yield span
            span.set_status("OK")
        except Exception:  # Compliant: the enclosing with releases span
            raise

Why is this an issue?

@contextmanager and @asynccontextmanager turn a generator into a context manager. The code before yield runs on enter, the with body runs at the yield, and the code after yield is meant to clean up on exit.

If cleanup sits after yield without a try/finally (or a nested with), it does not run when:

In those cases, resources such as files, locks, or connections can stay open.

A transaction is not a context manager, so it cannot be acquired with with.

from contextlib import contextmanager

@contextmanager
def transactional(connection):
    transaction = connection.begin()
    yield connection
    transaction.commit()  # Noncompliant: cleanup after "yield" may be skipped

If statements after yield are not cleanup (for example optional logging that is safe to skip), or cleanup is already guaranteed by a nested with or an enclosing try/finally the analyzer failed to see, treat that as a false positive. Marking a real resource release as won’t-fix is wrong: exceptions and early generator close can still skip those statements and leak the resource.

What is the potential impact?

Missed cleanup can leak resources, leave locks held, or leave shared state inconsistent. These failures often show up only under exceptions or early generator shutdown, which makes them harder to reproduce.

How to fix it

Wrap the yield so cleanup runs on every exit. Use try/finally, or except BaseException when success and failure need different actions. Nest a with only when the acquired object is itself a context manager.

Code examples

Noncompliant code example

from contextlib import contextmanager

@contextmanager
def transactional(connection):
    transaction = connection.begin()
    yield connection
    transaction.commit()  # Noncompliant: cleanup after "yield" may be skipped

Compliant solution

from contextlib import contextmanager

@contextmanager
def transactional(connection):
    transaction = connection.begin()
    try:
        yield connection
        transaction.commit()
    except BaseException:
        transaction.rollback()
        raise

Noncompliant code example

from contextlib import contextmanager

@contextmanager
def locked_section(lock):
    lock.acquire()
    yield
    lock.release()  # Noncompliant: "release" is skipped on exception

Compliant solution

from contextlib import contextmanager

@contextmanager
def locked_section(lock):
    with lock:
        yield

How does this work?

When an exception escapes the with body, Python resumes the generator at yield and re-raises there. A finally block still runs in that situation, and so does __exit__ for a nested with. Plain statements after yield do not.

Resources

Documentation

External coding guidelines