Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 12 additions & 0 deletions src/smolagents/local_python_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1627,6 +1627,18 @@ def evaluate_python_code(
state["_print_outputs"] = PrintContainer()
state["_operations_count"] = {"counter": 0}

# Bind the `print` tool to this run's print outputs so that every invocation
# is captured — including when `print` is passed around as a callback (e.g.
# `map(print, values)`), which bypasses the direct-call interception in
# `evaluate_call`. Direct `print(...)` calls behave exactly as before.
print_outputs = state["_print_outputs"]

def capturing_print(*args, **kwargs):
print_outputs.append(" ".join(map(str, args)) + "\n")
return None

static_tools["print"] = capturing_print

if "final_answer" in static_tools:
previous_final_answer = static_tools["final_answer"]

Expand Down
14 changes: 14 additions & 0 deletions tests/test_local_python_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,20 @@ def function():
evaluate_python_code(code, {"print": print, "range": range}, state=state)
assert state["_print_outputs"].value == "1\n2\n2\n2\n2\n2\n2\n2\n2\n2\n2\n"

def test_print_as_callback_is_captured(self):
# print passed as a callback (e.g. to map) must capture like a direct call
code = "list(map(print, ['red', 'blue']))"
state = {}
result, _ = evaluate_python_code(code, BASE_PYTHON_TOOLS, state=state)
assert result == [None, None]
assert state["_print_outputs"].value == "red\nblue\n"

# aliased print must capture as well
code = "f = print\nf('aliased')"
state = {}
evaluate_python_code(code, BASE_PYTHON_TOOLS, state=state)
assert state["_print_outputs"].value == "aliased\n"

def test_tuple_target_in_iterator(self):
code = "for a, b in [('Ralf Weikert', 'Austria'), ('Samuel Seungwon Lee', 'South Korea')]:res = a.split()[0]"
result, _ = evaluate_python_code(code, BASE_PYTHON_TOOLS, state={})
Expand Down