Skip to content
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

gh-99606: Make code generated for an empty f-string identical to that of a normal empty string #112407

Merged
merged 5 commits into from
Nov 26, 2023
Merged
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
10 changes: 10 additions & 0 deletions Lib/test/test_fstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# Unicode identifiers in tests is allowed by PEP 3131.

import ast
import dis
import os
import re
import types
Expand Down Expand Up @@ -1738,5 +1739,14 @@ def test_syntax_warning_infinite_recursion_in_file(self):
self.assertIn(rb'\1', stdout)
self.assertEqual(len(stderr.strip().splitlines()), 2)

def test_fstring_without_formatting_bytecode(self):
# f-string without any formatting should emit the same bytecode
# as a normal string. See gh-99606.
def get_code(s):
return [(i.opname, i.oparg) for i in dis.get_instructions(s)]

for s in ["", "some string"]:
self.assertEqual(get_code(f"'{s}'"), get_code(f"f'{s}'"))

if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Make code generated for an empty f-string identical to the code of an empty
normal string.
8 changes: 6 additions & 2 deletions Python/compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -5042,8 +5042,12 @@ compiler_joined_str(struct compiler *c, expr_ty e)
}
else {
VISIT_SEQ(c, expr, e->v.JoinedStr.values);
if (asdl_seq_LEN(e->v.JoinedStr.values) != 1) {
ADDOP_I(c, loc, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
if (value_count > 1) {
ADDOP_I(c, loc, BUILD_STRING, value_count);
}
else if (value_count == 0) {
_Py_DECLARE_STR(empty, "");
ADDOP_LOAD_CONST_NEW(c, loc, Py_NewRef(&_Py_STR(empty)));
}
}
return SUCCESS;
Expand Down
Loading