Property layers can break
Grid.create_property_layer() / Grid.add_property_layer() are supposed to reject a
property-layer name that collides with an existing attribute, so that attaching a
layer can never silently break cell-level access. The collision check in
Grid._attach_property_layer() (mesa/discrete_space/grid.py:184-202) only checks
type(self) — the Grid's own class — and self.cell_klass.__slots__. It never
checks the actual attributes defined on self.cell_klass (the Cell/GridCell
subclass), which is the class that gets mutated via setattr(self.cell_klass, name, accessor)
a few lines later.
As a result, creating a property layer named is_empty, is_full, neighborhood,
or position — all real @property accessors on Cell (mesa/discrete_space/cell.py)
— silently overwrites them with a static, array-backed accessor, with no error or
warning. Since DiscreteSpace.empties and Grid.cells_with_capacity depend on
cell.is_empty / cell.is_full being computed live from the cell's actual agent
list, this corrupts occupancy and capacity queries for the rest of the model's life.
Expected behavior
Calling grid.create_property_layer("is_full", ...) (or is_empty, neighborhood,
position) should raise a ValueError, exactly as it already does today for
Grid-level attribute names like "capacity" and "width":
with pytest.raises(ValueError):
grid.create_property_layer("capacity", 1, dtype=int)
To Reproduce
import mesa
from mesa.discrete_space import OrthogonalMooreGrid, CellAgent
class MyModel(mesa.Model):
def __init__(self):
super().__init__(rng=1)
self.grid = OrthogonalMooreGrid((3, 3), torus=False, capacity=1, random=self.random)
m = MyModel()
print("empties before:", len(m.grid.empties))
m.grid.create_property_layer("is_empty", default_value=False, dtype=bool)
print("empties after:", len(m.grid.empties))
m2 = MyModel()
m2.grid.create_property_layer("is_full", default_value=False, dtype=bool)
c2 = m2.grid._cells[(1, 1)]
CellAgent(m2).cell = c2
print("is_full (should be True):", c2.is_full)
print("cells_with_capacity (should be 8):", len(list(m2.grid.cells_with_capacity)))
Output on current main (e5c3b38d):
empties before: 9
empties after: 0
is_full (should be True): False
cells_with_capacity (should be 8): 9
No exception is raised anywhere in this run — the corruption is silent.
Additional context
- File/lines:
mesa/discrete_space/grid.py:184-202(Grid._attach_property_layer). - Existing tests (
tests/discrete_space/test_discrete_space.py:896-919) only cover collisions with Grid-level attributes (capacity,width), not Cell-level accessors, so this gap has no test coverage today. - Not limited to the four names above: any custom
cell_klasswith its own@property/method hits the same silent corruption if a property layer is later created with a matching name, sincecell_klassis never consulted by the check. - Related but distinct: #3072 ("Make
cell.emptyread only") is about direct assignment tocell.empty, not this name-collision path. - Impact: any model using
grid.empties,select_random_empty_cell(), orcells_with_capacityafter creating a colliding property layer will get silently wrong occupancy/capacity results (agents placed over capacity, or aLookupErrorfromrandom.choice(list(self.empties))on a grid that isn't actually full).
Proposed fix
Extend the collision check in Grid._attach_property_layer() to also inspect
self.cell_klass.__mro__, not just type(self) (the Grid) and the cell's
__slots__. The one name that must stay allowed is "empty", since
Grid.__init__ itself installs a property layer under that name to back
Cell.empty:
# mesa/discrete_space/grid.py, inside _attach_property_layer
cell_attrs = set(
chain.from_iterable(c.__dict__ for c in self.cell_klass.__mro__)
)
if name != "empty" and name in cell_attrs:
raise ValueError(
f"property_layer '{name}' conflicts with an existing Cell attribute."
)
This mirrors the existing slots check immediately below it and keeps the same
ValueError contract callers already rely on for capacity/width collisions.
Suggested regression test
Add to tests/discrete_space/test_discrete_space.py, next to the existing
capacity/width conflict test:
@pytest.mark.parametrize(
"reserved", ["is_empty", "is_full", "neighborhood", "position"]
)
def test_property_layer_rejects_cell_attribute_collision(reserved):
grid = OrthogonalMooreGrid((3, 3), torus=False, capacity=1, random=random.Random(1))
with pytest.raises(ValueError):
grid.create_property_layer(reserved, default_value=False, dtype=bool)
# occupancy must still be computed correctly after the rejection
assert len(grid.empties) == 9
@EdwardBetts can you please review this !