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
18 changes: 14 additions & 4 deletions src/smolagents/local_python_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1493,10 +1493,20 @@ def evaluate_ast(
elif isinstance(expression, ast.FunctionDef):
return evaluate_function_def(expression, *common_params)
elif isinstance(expression, ast.Dict):
# Dict -> evaluate all keys and values
keys = (evaluate_ast(k, *common_params) for k in expression.keys)
values = (evaluate_ast(v, *common_params) for v in expression.values)
return dict(zip(keys, values))
# Dict -> evaluate all keys and values; a None key marks a `**mapping` entry to merge
result = {}
for key_node, value_node in zip(expression.keys, expression.values):
if key_node is None:
value = evaluate_ast(value_node, *common_params)
# CPython gates `{**obj}` on the mapping protocol, not the Mapping ABC:
# any object with `keys()` is accepted, pair iterables are not.
if not hasattr(value, "keys"):
raise InterpreterError(f"'{type(value).__name__}' object is not a mapping")
result.update(value)
else:
key = evaluate_ast(key_node, *common_params)
result[key] = evaluate_ast(value_node, *common_params)
return result
elif isinstance(expression, ast.Expr):
# Expression -> evaluate the content
return evaluate_ast(expression.value, *common_params)
Expand Down
36 changes: 36 additions & 0 deletions tests/test_local_python_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,42 @@ def test_evaluate_dict(self):
state, {"x": 3, "test_dict": {"x": 3, "y": 5}, "_operations_count": {"counter": 7}}
)

@pytest.mark.parametrize(
"code, expected",
[
("{**{'a': 1}, 'b': 2}", {"a": 1, "b": 2}),
("{**{'a': 1}, **{'b': 2}}", {"a": 1, "b": 2}),
("{**{'a': 1}, 'a': 2}", {"a": 2}),
("{'a': 0, **{'a': 1}}", {"a": 1}),
("base = {'x': 1}\n{**base, 'y': 2}", {"x": 1, "y": 2}),
("{**{}}", {}),
],
)
def test_evaluate_dict_unpacking(self, code, expected):
result, _ = evaluate_python_code(code, {}, state={})
assert result == expected

def test_evaluate_dict_unpacking_accepts_mapping_protocol_objects(self):
code = dedent(
"""
class MyMap:
def keys(self):
return ["a"]

def __getitem__(self, key):
return 1

{**MyMap(), "b": 2}
"""
)
result, _ = evaluate_python_code(code, {}, state={})
assert result == {"a": 1, "b": 2}

@pytest.mark.parametrize("code", ["{**[1, 2]}", "{**[('a', 1)]}"])
def test_evaluate_dict_unpacking_non_mapping_raises(self, code):
with pytest.raises(InterpreterError, match="object is not a mapping"):
evaluate_python_code(code, {}, state={})

def test_evaluate_expression(self):
code = "x = 3\ny = 5"
state = {}
Expand Down