Skip to content

No SyntaxWarning for return in a loop inside a finally block #162575

Backlog

Description

@Robertboy18

Bug report

Bug description:

return in a finally block gives SyntaxWarning: 'return' in a 'finally' block, also under an if, but not when it is inside a for or while loop in the finally block, although it leaves the finally block and swallows the exception all the same:

import warnings
for body in ("if True:", "for i in (1,):", "while True:"):
    src = ("def f():\n    try:\n        raise KeyError\n    finally:\n"
           "        " + body + "\n            return 'returned'\n")
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")
        ns = {}
        exec(compile(src, "<s>", "exec"), ns)
    print(body, [str(x.message) for x in w], ns["f"]())
if True: ["'return' in a 'finally' block"] returned
for i in (1,): [] returned
while True: [] returned

The docs say "The compiler emits a SyntaxWarning when a return, break or continue appears in a finally block (see PEP 765)" (finally clause). In Python/ast_preprocess.c, BEFORE_LOOP_BODY pushes a context with in_finally false, which is right for break and continue, but before_return only looks at that top context. I found it while writing a Lean spec of Python.

CPython versions tested on:

3.15, CPython main branch

Operating systems tested on:

Linux

Activity

  1. added
    interpreter-core
    type-bug
    on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions