mesa icon indicating copy to clipboard operation
mesa copied to clipboard

add_row() mutates the caller's input dictionary via row.pop(), causing KeyError on reuse

Open Krishsharma179 opened this issue 7 months ago • 0 comments

Describe the bug

add_row() mutates the caller's input dictionary by using row.pop() internally, which removes keys from the original dict passed by the user. This causes a KeyError on subsequent uses of the same row dict.

Expected behavior add_row() should not modify the dictionary passed in by the caller. The original row dict should remain intact after the call

To Reproduce Steps to reproduce the bug, or a link to a project where the bug is visible

from mesa.experimental.data_collection.dataset import TableDataSet

data_set = TableDataSet("t", fields=["a", "b"])

row = {'a': 1, 'b': 2}

for i in range(10):
    row['a'] = row['a'] * i
    row['b'] = row['b'] * i
    data_set.add_row(row)  # After first call, row is emptied KeyError on next iteration

print(data_set.data)

Just run this you will see an error it works fine when the row is added one time but raise error on the second time

Additional context

The bug is in add_row() in dataset.py, specifically this line:

row_to_add= {k: row.pop(k) for k in self.fields}

dict.pop() removes the key from the original dict. It should be changed to: python row_to_add = {k: row[k] for k in self.fields} This reads the values without mutating the caller's dictionary.

I already have an implementation for this I will be submitting a PR shortly. And I'd love to hear other perspectives

Krishsharma179 avatar Apr 03 '26 16:04 Krishsharma179