Issue 29814: parsing f-strings -- opening brace of expression gets duplicated when preceeded by backslash (original) (raw)
with Python 3.6.0 and the following script:
#!/usr/bin/env python3.6
import ast
code1 = '''"\\{x}"'''
code2 = '''f"\\{x}"'''
tree1 = ast.parse(code1, mode='eval')
print(ast.dump(tree1))
tree2 = ast.parse(code2, mode='eval')
print(ast.dump(tree2))
I get the following output:
Expression(body=Str(s='\\{x}'))
Expression(body=JoinedStr(values=[Str(s='\\{'), FormattedValue(value=Name(id='x', ctx=Load()), conversion=-1, format_spec=None)]))
Therefore, the normal string is '\\{x}'
.
But the f-string has two parts: '\\{'
and an expression Name(id='x', ctx=Load())
.
Where does the {
in the string part of f-string come from? I can't believe this is the intended behavior... Or, is it?
When I escape the backslash once like above, what gets parsed is actually unescaped backslash. So this might just boil down to inconsistency in parsing \{
in normal vs. f-strings.
I originally discovered this in typed_ast https://github.com/python/typed_ast/issues/34 but the behaviour of ast is identical and since developers of typed_ast aim at compatibility with ast, I bring this issue here.