Skip to content
Open
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
22 changes: 16 additions & 6 deletions py_backwards/transformers/formatted_values.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import functools

from typed_ast import ast3 as ast
from ..const import TARGET_ALL
from .base import BaseNodeTransformer
Expand All @@ -7,7 +9,7 @@ class FormattedValuesTransformer(BaseNodeTransformer):
"""Compiles:
f"hello {x}"
To
''.join(['hello ', '{}'.format(x)])
'hello ' + '{}'.format(x)

"""
target = TARGET_ALL
Expand All @@ -28,9 +30,17 @@ def visit_FormattedValue(self, node: ast.FormattedValue) -> ast.Call:

def visit_JoinedStr(self, node: ast.JoinedStr) -> ast.Call:
self._tree_changed = True
NONE = ast.Str(s='')

init = ast.BinOp(left=NONE, right=NONE, op=ast.Add())

def to_binop(acc, next):
left, right, op = acc.left, acc.right, acc.op
if left is NONE:
return ast.BinOp(left=right, right=next, op=op)
return ast.BinOp(left=acc, right=next, op=op)

value = functools.reduce(to_binop, node.values, init)
concat_expr = ast.Expr(value=value)

join_call = ast.Call(func=ast.Attribute(value=ast.Str(s=''),
attr='join'),
args=[ast.List(elts=node.values)],
keywords=[])
return self.generic_visit(join_call) # type: ignore
return self.generic_visit(concat_expr) # type: ignore
5 changes: 3 additions & 2 deletions tests/transformers/test_formatted_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

@pytest.mark.parametrize('before, after', [
("f'hi'", "'hi'"),
("f'hi {x}'", "''.join(['hi ', '{}'.format(x)])"),
("f'hi {x}'", "'hi ' + '{}'.format(x)"),
("d = f'{a} {b}!'", "d = '{}'.format(a) + ' ' + '{}'.format(b) + '!'"),
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't work out why this becomes:

d = 
'{}'.format(a) + ' ' + '{}'.format(b) + '!'

("f'hi {x.upper()} {y:1}'",
"''.join(['hi ', '{}'.format(x.upper()), ' ', '{:1}'.format(y)])")])
"'hi ' + '{}'.format(x.upper()) + ' ' + '{:1}'.format(y)")])
def test_transform(transform, ast, before, after):
code = transform(FormattedValuesTransformer, before)
assert ast(code) == ast(after)
Expand Down