Skip to content

Commit b98cf95

Browse files
committed
added empty iterable checks and updated tests
1 parent dbb9264 commit b98cf95

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

mesa/batchrunner.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,16 @@ def _make_model_kwargs(
106106
Parameters
107107
----------
108108
parameters : Mapping[str, Union[Any, Iterable[Any]]]
109-
Single or multiple values for each model parameter name
109+
Single or multiple values for each model parameter name.
110110
111-
Returns:
111+
Allowed values for each parameter:
112+
- A single value (e.g., `32`, `"relu"`).
113+
- A non-empty iterable (e.g., `[0.01, 0.1]`, `["relu", "sigmoid"]`).
114+
115+
Not allowed:
116+
- Empty lists or empty iterables (e.g., `[]`, `()`, etc.). These should be removed manually.
117+
118+
Returns
112119
-------
113120
List[Dict[str, Any]]
114121
A list of all kwargs combinations.
@@ -118,6 +125,10 @@ def _make_model_kwargs(
118125
if isinstance(values, str):
119126
# The values is a single string, so we shouldn't iterate over it.
120127
all_values = [(param, values)]
128+
elif isinstance(values, list | tuple | set) and len(values) == 0:
129+
# If it's an empty iterable, raise an error
130+
raise ValueError(f"Parameter '{param}' contains an empty iterable, which is not allowed.")
131+
121132
else:
122133
try:
123134
all_values = [(param, value) for value in values]

tests/test_batch_run.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,34 @@ def test_make_model_kwargs(): # noqa: D103
2424
assert _make_model_kwargs({"a": "value"}) == [{"a": "value"}]
2525

2626

27+
def test_batch_run_with_params_with_empty_content():
28+
"""Test handling of empty iterables in model kwargs."""
29+
30+
# If "a" is a single value and "b" is an empty list (should raise error for the empty list)
31+
parameters_with_empty_list = {
32+
"a": 3,
33+
"b": [],
34+
}
35+
36+
try:
37+
_make_model_kwargs(parameters_with_empty_list)
38+
raise AssertionError("Expected ValueError for empty iterable but no error was raised.")
39+
except ValueError as e:
40+
assert "contains an empty iterable" in str(e)
41+
42+
# If "a" is a iterable and "b" is an empty list (should still raise error)
43+
parameters_with_empty_b = {
44+
"a": [1, 2],
45+
"b": [],
46+
}
47+
48+
try:
49+
_make_model_kwargs(parameters_with_empty_b)
50+
raise AssertionError("Expected ValueError for empty iterable but no error was raised.")
51+
except ValueError as e:
52+
assert "contains an empty iterable" in str(e)
53+
54+
2755
class MockAgent(Agent):
2856
"""Minimalistic agent implementation for testing purposes."""
2957

0 commit comments

Comments
 (0)