Skip to content

Commit fb202af

Browse files
authored
gh-99606: Make code generated for an empty f-string identical to that of a normal empty string (#112407)
1 parent 418d585 commit fb202af

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

Lib/test/test_fstring.py

+10
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
# Unicode identifiers in tests is allowed by PEP 3131.
99

1010
import ast
11+
import dis
1112
import os
1213
import re
1314
import types
@@ -1738,5 +1739,14 @@ def test_syntax_warning_infinite_recursion_in_file(self):
17381739
self.assertIn(rb'\1', stdout)
17391740
self.assertEqual(len(stderr.strip().splitlines()), 2)
17401741

1742+
def test_fstring_without_formatting_bytecode(self):
1743+
# f-string without any formatting should emit the same bytecode
1744+
# as a normal string. See gh-99606.
1745+
def get_code(s):
1746+
return [(i.opname, i.oparg) for i in dis.get_instructions(s)]
1747+
1748+
for s in ["", "some string"]:
1749+
self.assertEqual(get_code(f"'{s}'"), get_code(f"f'{s}'"))
1750+
17411751
if __name__ == '__main__':
17421752
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Make code generated for an empty f-string identical to the code of an empty
2+
normal string.

Python/compile.c

+6-2
Original file line numberDiff line numberDiff line change
@@ -5042,8 +5042,12 @@ compiler_joined_str(struct compiler *c, expr_ty e)
50425042
}
50435043
else {
50445044
VISIT_SEQ(c, expr, e->v.JoinedStr.values);
5045-
if (asdl_seq_LEN(e->v.JoinedStr.values) != 1) {
5046-
ADDOP_I(c, loc, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
5045+
if (value_count > 1) {
5046+
ADDOP_I(c, loc, BUILD_STRING, value_count);
5047+
}
5048+
else if (value_count == 0) {
5049+
_Py_DECLARE_STR(empty, "");
5050+
ADDOP_LOAD_CONST_NEW(c, loc, Py_NewRef(&_Py_STR(empty)));
50475051
}
50485052
}
50495053
return SUCCESS;

0 commit comments

Comments
 (0)