Skip to content

The agent engineering platform.

refactor(core): generalize `comma_list` utility to support any `Iterable` (#34714)

David Fernandez5b401fa4143c
diff --git a/libs/core/langchain_core/utils/strings.py b/libs/core/langchain_core/utils/strings.py
index 9326bc0662..00c565a936 100644
--- a/libs/core/langchain_core/utils/strings.py
+++ b/libs/core/langchain_core/utils/strings.py
@@ -1,5 +1,6 @@
"""String utilities."""
+from collections.abc import Iterable
from typing import Any
@@ -33,11 +34,11 @@ def stringify_dict(data: dict) -> str:
return "".join(f"{key}: {stringify_value(value)}\n" for key, value in data.items())
-def comma_list(items: list[Any]) -> str:
- """Convert a list to a comma-separated string.
+def comma_list(items: Iterable[Any]) -> str:
+ """Convert an iterable to a comma-separated string.
Args:
- items: The list to convert.
+ items: The iterable to convert.
Returns:
The comma-separated string.
diff --git a/libs/core/tests/unit_tests/utils/test_strings.py b/libs/core/tests/unit_tests/utils/test_strings.py
index 9e94517cec..a8ed1fff7f 100644
--- a/libs/core/tests/unit_tests/utils/test_strings.py
+++ b/libs/core/tests/unit_tests/utils/test_strings.py
@@ -79,3 +79,26 @@ def test_stringify_value_nested_structures() -> None:
assert "key: value" in result
assert "nested" in result
assert "list" in result
+
+
+def test_comma_list_with_iterables() -> None:
+ """Test `comma_list` works with various iterable types."""
+ # Tuple
+ assert comma_list((1, 2, 3)) == "1, 2, 3"
+
+ # Generator
+ assert comma_list(x for x in range(3)) == "0, 1, 2"
+
+ # Range
+ assert comma_list(range(3)) == "0, 1, 2"
+
+ # Empty iterable
+ assert comma_list([]) == ""
+ assert comma_list(()) == ""
+
+ # Single item
+ assert comma_list([1]) == "1"
+ assert comma_list(("single",)) == "single"
+
+ # Mixed types
+ assert comma_list([1, "two", 3.0]) == "1, two, 3.0"