Respect formatting in ast.FormattedValue for local_python_executor (#660)

Co-authored-by: Ilya Amelchenkov <ilya@fstr.app>
Co-authored-by: Albert Villanova del Moral <8515462+albertvillanova@users.noreply.github.com>
This commit is contained in:
Ilya Amelchenkov 2025-02-18 17:15:11 +02:00 committed by GitHub
parent 46a5d6cc0c
commit 3772f1a96a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 2 deletions

View File

@ -1229,8 +1229,14 @@ def evaluate_ast(
# For loop -> execute the loop # For loop -> execute the loop
return evaluate_for(expression, *common_params) return evaluate_for(expression, *common_params)
elif isinstance(expression, ast.FormattedValue): elif isinstance(expression, ast.FormattedValue):
# Formatted value (part of f-string) -> evaluate the content and return # Formatted value (part of f-string) -> evaluate the content and format it
return evaluate_ast(expression.value, *common_params) value = evaluate_ast(expression.value, *common_params)
# Early return if no format spec
if not expression.format_spec:
return value
# Apply format specification
format_spec = evaluate_ast(expression.format_spec, *common_params)
return format(value, format_spec)
elif isinstance(expression, ast.If): elif isinstance(expression, ast.If):
# If -> execute the right branch # If -> execute the right branch
return evaluate_if(expression, *common_params) return evaluate_if(expression, *common_params)

View File

@ -122,6 +122,22 @@ class PythonInterpreterTester(unittest.TestCase):
assert result == "This is x: 3." assert result == "This is x: 3."
self.assertDictEqualNoPrint(state, {"x": 3, "text": "This is x: 3.", "_operations_count": 6}) self.assertDictEqualNoPrint(state, {"x": 3, "text": "This is x: 3.", "_operations_count": 6})
def test_evaluate_f_string_with_format(self):
code = "text = f'This is x: {x:.2f}.'"
state = {"x": 3.336}
result, _ = evaluate_python_code(code, {}, state=state)
assert result == "This is x: 3.34."
self.assertDictEqualNoPrint(state, {"x": 3.336, "text": "This is x: 3.34.", "_operations_count": 8})
def test_evaluate_f_string_with_complex_format(self):
code = "text = f'This is x: {x:>{width}.{precision}f}.'"
state = {"x": 3.336, "width": 10, "precision": 2}
result, _ = evaluate_python_code(code, {}, state=state)
assert result == "This is x: 3.34."
self.assertDictEqualNoPrint(
state, {"x": 3.336, "width": 10, "precision": 2, "text": "This is x: 3.34.", "_operations_count": 14}
)
def test_evaluate_if(self): def test_evaluate_if(self):
code = "if x <= 3:\n y = 2\nelse:\n y = 5" code = "if x <= 3:\n y = 2\nelse:\n y = 5"
state = {"x": 3} state = {"x": 3}