A generator context manager's cleanup after yield is skipped when the block raises
What it finds
A @contextmanager function with code after its yield that is not in a finally block or a with statement: when the body of the with that uses it raises, the exception comes out of the yield, and the cleanup after it never runs. Wrapping the yield in try: ... finally: runs it either way.
Reported are generators decorated with contextmanager or asynccontextmanager whose yield is not inside a try with finally or a with, and that have statements after the yield.
From the rule's source, yield_without_finally.rs.
from contextlib import contextmanager @contextmanagerdef opened(path): handle = open(path) yield handletx0 reports: the code after this yield does not run when the with block raises handle.close() @contextmanagerdef safe(path): handle = open(path) try: yield handle finally: handle.close() @contextmanagerdef nothing_after(): yield 1 Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/python:yield-without-finally" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
# tx0: ignore[tx0/python:yield-without-finally] reason="..."tx0 explain tx0/python:yield-without-finally shows the same in the terminal. Found a false positive? Report it.