Skip to content

Commit

Permalink
pythongh-124022: Fix extrenous NOP when class docstring is removed in…
Browse files Browse the repository at this point in the history
… interactive mode
  • Loading branch information
iritkatriel committed Sep 12, 2024
1 parent 6e06e01 commit a4da842
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
18 changes: 18 additions & 0 deletions Lib/test/test_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,24 @@ class C:
dis.dis(code)
self.assertNotIn('NOP' , output.getvalue())

@support.cpython_only
def test_docstring_removed_no_NOP_interactive_mode(self):
# See gh-124022
src = textwrap.dedent("""
class C:
"docstring"
x = 42
""")
for opt in [-1, 0, 1, 2]:
with self.subTest(opt=opt):
code = compile(src, "<test>", "single", optimize=opt)
# make sure the bytecode doesn't have any instruction
# on line 3, where the docstring is, but we have
# instructions for the assignment in line 4.
lines = [line for (_, _, line) in code.co_consts[0].co_lines()]
self.assertNotIn(3, lines)
self.assertIn(4, lines)

def test_dont_merge_constants(self):
# Issue #25843: compile() must not merge constants which are equal
# but have a different type.
Expand Down
8 changes: 4 additions & 4 deletions Python/codegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -758,10 +758,10 @@ _PyCodegen_Body(compiler *c, location loc, asdl_stmt_seq *stmts)
return SUCCESS;
}
Py_ssize_t first_instr = 0;
if (!IS_INTERACTIVE(c)) {
PyObject *docstring = _PyAST_GetDocString(stmts);
if (docstring) {
first_instr = 1;
PyObject *docstring = _PyAST_GetDocString(stmts);
if (docstring) {
first_instr = 1;
if (!IS_INTERACTIVE(c)) {
/* set docstring */
assert(OPTIMIZATION_LEVEL(c) < 2);
PyObject *cleandoc = _PyCompile_CleanDoc(docstring);
Expand Down

0 comments on commit a4da842

Please sign in to comment.