Skip to content

gh-79932: do not allow to clear a suspended frame #98834

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Lib/test/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
import sys
import textwrap
import traceback
import types
import unittest
import weakref
Expand Down Expand Up @@ -111,6 +112,25 @@ def g():
f.clear()
self.assertTrue(endly)

def test_clear_suspended_generator(self):
# Attempting to clear a suspended generator frame is forbidden.
def g():
for i in range(5):
try:
1/0
except ZeroDivisionError as e:
yield (e, i)

gen = g()
res = []
for e, i in gen:
res.append(i)
with self.assertRaises(RuntimeError):
f = e.__traceback__.tb_frame
self.assertIsNotNone(f)
f.clear()
self.assertEqual(res, list(range(5)))

def test_lineno_with_tracing(self):
def record_line():
f = sys._getframe(1)
Expand Down
3 changes: 2 additions & 1 deletion Objects/frameobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -949,7 +949,8 @@ frame_clear(PyFrameObject *f, PyObject *Py_UNUSED(ignored))
{
if (f->f_frame->owner == FRAME_OWNED_BY_GENERATOR) {
PyGenObject *gen = _PyFrame_GetGenerator(f->f_frame);
if (gen->gi_frame_state == FRAME_EXECUTING) {
if (gen->gi_frame_state == FRAME_EXECUTING ||
gen->gi_frame_state == FRAME_SUSPENDED) {
goto running;
}
_PyGen_Finalize((PyObject *)gen);
Expand Down