Skip to content

gh-162575: Warn about return in a loop in a finally block - #162591

Open
zeyadrabie wants to merge 1 commit into
python:mainfrom
zeyadrabie:gh-162575-return-in-loop-in-finally
Open

zeyadrabie wants to merge 1 commit into
python:mainfrom
zeyadrabie:gh-162575-return-in-loop-in-finally

Conversation

@zeyadrabie

@zeyadrabie zeyadrabie commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

before_return() in Python/ast_preprocess.c only checked the innermost context. A for or while loop inside a finally block masked the enclosing finally, suppressing the PEP 765 SyntaxWarning.

This updates before_return() to walk past loop contexts, warning on the first finally and stopping at a function body. break and continue keep the existing check. In a loop inside finally, the loop catches them, so they don't leave the finally block.

Added tests in test_syntax that fail without the fix, and a no-warning case in test_compile. The full test suite passes, and ./python -W error::SyntaxWarning -m compileall -f Lib shows no new warnings in the standard library.

I utilized Claude Code (Opus 5.5) to draft and test, and I reviewed the diff and the results afterwards myself.

before_return() only checked the innermost context, so a loop inside a
finally block hid the finally. Walk past loop contexts until a finally
block or function body.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant