SyntaxError at line -1 for a `break` inside a `with` block in an `except*` block · Issue #163224 · python/cpython
Repository navigation
SyntaxError at line -1 for a break inside a with block in an except* block #163224
New issue
New issue
Backlog
#163225
Backlog
SyntaxError at line -1 for a
break inside a with block in an except* block #163224
#163225
Labels
interpreter-core
type-bug
Description
@Robertboy18's profile Robertboy18 opened on Dec 6, 2026Bug report
I came across this while working on a Lean formalization of the Python spec. A break, continue or return in an except* block is rejected, as documented, but when the statement sits inside a with block the SyntaxError loses its location:
for x in []:
try:
pass
except* ValueError:
with open("f"):
break
File "repro.py", line -1
SyntaxError: 'break', 'continue' and 'return' cannot appear in an except* block
That's on main (c76d734), and 3.15.2, 3.13.15 and 3.12.16 print the same. lineno is -1 and offset is 0, so there's no source line or caret. Without the with, the error points at line 5 with a caret under break. It also happens inside async with, and inside the body or an except clause of a try that has a finally.
I think the issue is in Python/codegen.c. After unwinding a with (line 627) or a try/finally (line 595), codegen_unwind_fblock() sets *ploc to NO_LOCATION so the unwinding instructions are artificial, and codegen_unwind_fblock_stack() then raises the except* error with that location on a later step (lines 666-668). gh-101400 was the same "line -1" for 'break' outside loop, and its fix keeps an origin_loc in codegen_break() and codegen_continue(), so I'd guess this error just needs the statement's own location too. The invalid-code tests in TestBreakContinueReturnInExceptStarBlock check the message but not the location, so a new case with a nested with and a lineno check would cover this.
Happy to send a PR :)
CPython versions tested on:
3.12, 3.13, 3.15, CPython main branch
Operating systems tested on:
Linux
Linked PRs
Metadata
Metadata
Assignees
No one assignedLabels
interpreter-core
type-bug