Make `cell.empty` read only
What's the problem this feature will solve?
Currently, cells have two ways of getting their full/empty state: cell.empty and cell.is_empty. The former is a view into the underlying empty property layer on the space. The latter is the actual check if self-agents are empty.
It is easy to invalidate the property layer by setting cell.empty directly yourself, and since it is part of the public API, nothing will warn the user or prevent the user from doing so
Describe the solution you'd like Ideally, we add a way to add read-only property layer descriptors, while still allowing the cell to privately change its value.
Additional context See also #3068 for more background on this.
Good idea! I can implement this with:
- New
ReadOnlyPropertyDescriptorclass (raises error on write) - Add
_spacereference to cells - Internal
_update_property()method for managed properties - Mark
emptylayer as read-only
This prevents users from doing cell.empty = False while still allowing internal updates via add_agent/remove_agent. Reading remains backward compatible.
Happy to work on a PR if this approach works for you!
I am not sure that the sketched outline is what I prefer. Most notably, we deliberately made Cell unaware of the space, so adding _space runs counter to a key design choice. Also, I prefer to have a generic solution in place so you can mark any property layer as read-only.
I propose implementing a read-only interface with a private backing field. This effectively mimics standard Python encapsulation (where a public read-only property exposes a private writable attribute), adapted dynamically for the PropertyLayer system.
This solves the issue without introducing new classes, simply by extending the existing PropertyDescriptor.
The Proposal
We configure the system so that the Grid attaches two descriptors to the Cell for the same data layer:
- Public Interface (
cell.empty): A Read-Only descriptor. This prevents users from manually invalidating the state. - Private Backing (
cell._empty): A Writable descriptor. TheCelluses this internal attribute to manage its state.
Implementation Details
1. mesa/discrete_space/property_layer.py
We modify PropertyDescriptor to accept a read_only flag and update HasPropertyLayers to wire up the private backing descriptor automatically.
# Modified PropertyDescriptor
class PropertyDescriptor:
def __init__(self, property_layer: PropertyLayer, read_only: bool = False):
self.layer = property_layer
self._read_only = read_only
def __get__(self, instance: Cell, owner):
return self.layer.data[instance.coordinate]
def __set__(self, instance: Cell, value):
if self._read_only:
raise AttributeError(
f"Property '{self.layer.name}' is read-only. "
"Use the internal attribute to modify it."
)
self.layer.data[instance.coordinate] = value
# Modified HasPropertyLayers logic
class HasPropertyLayers:
def add_property_layer(self, layer: PropertyLayer, read_only: bool = False):
# ... [existing validation] ...
self._mesa_property_layers[layer.name] = layer
if read_only:
# 1. Public Interface (Read-Only)
setattr(self.cell_klass, layer.name,
PropertyDescriptor(layer, read_only=True))
# 2. Private Backing (Writable)
# This allows the Cell to update the layer via self._name
setattr(self.cell_klass, "_" + layer.name,
PropertyDescriptor(layer, read_only=False))
else:
setattr(self.cell_klass, layer.name,
PropertyDescriptor(layer, read_only=False))
2. mesa/discrete_space/cell.py
We decouple Cell from the Grid by making it strictly rely on its internal _underscore attribute. We also add a fallback so Cell continues to function correctly in spaces without property layers (like Network).
class Cell:
def __init__(self, coordinate, capacity=None, random=None):
# ... [existing init] ...
# In a Grid, this is immediately 'hooked' by the private descriptor.
# In a Network, this remains a standard instance attribute.
self._empty = True
# Fallback property for spaces without PropertyLayers
@property
def empty(self) -> bool:
return self._empty
def add_agent(self, agent: CellAgent) -> None:
# ... [existing checks] ...
self._agents.append(agent)
# CRITICAL UPDATE
self._empty = False
def remove_agent(self, agent: CellAgent) -> None:
self._agents.remove(agent)
# CRITICAL UPDATE
self._empty = self.is_empty
3. mesa/discrete_space/grid.py
Finally, we simply flip the switch when the Grid initializes the layer.
class Grid(DiscreteSpace[T], HasPropertyLayers):
def __init__(self, ...):
# ...
self._connect_cells()
# Mark 'empty' as read-only.
# This triggers the creation of both 'cell.empty' (read-only) and 'cell._empty' (writable).
self.create_property_layer("empty", default_value=True, dtype=bool, read_only=True)
Pros
- Decoupling:
Celldoes not knowGridexists. It simply writes toself._empty. - Safety:
cell.empty = Falsenow raises anAttributeError, protecting data integrity. - Simplicity: No new classes are introduced; we just extend
PropertyDescriptorwith a flag.
An additional benefit is that this pattern abstracts the storage mechanism. If we later refactor PropertyLayer to be a raw NumPy array (as discussed in #3067 ), the Cell implementation (self._empty = False) will not need to change; only the Descriptor's internal logic would need to be updated.
Some quick comments:
- I agree on adding a boolean kwarg to PropertyLayer to indicate whether it's read-only or not
- I prefer 2 descriptors over a single one with an if-statement in it.
- I dislike the idea of adding 2 descriptors for creating private access. I need to examine this more closely, but it should be possible to fix it more elegantly. If one of us can figure this out, it might also make the case for having both
PropertyDescriptorandReadOnlyPropertyDescriptorstronger.
I think this can be resolved cleanly by separating read-only semantics from mutation, without adding Cell–Space coupling or duplicating descriptors.
Proposed direction:
- Make PropertyDescriptor always read-only. Its sole responsibility is exposing a view of the underlying layer.
- Move write control into PropertyLayer itself via an explicit internal mutation API.
- Mark layers as read_only=True, and allow updates only through an internal call path (e.g. layer.set_value(coord, value, internal=True)), used by Grid/Space internals when agent state changes.
This keeps:
- Cell unaware of Space or property layers
- exactly one descriptor per property
- a generic, opt-in read-only mechanism for any layer
- a clear separation of concerns (descriptor = view, layer = storage + rules)
It also avoids private shadow attributes or naming conventions, and makes future storage refactors easier since mutation is centralized in PropertyLayer
Design
PropertyDescriptorbecomes read-only by definitionPropertyLayerowns mutation logic and enforces read-only rules- Internal updates are performed explicitly by Grid/Space internals
- No duplicate descriptors
- No private shadow attributes
- No new Cell ↔ Space coupling
Changes
1. PropertyLayer: add read-only flag and internal mutation API
class PropertyLayer:
def __init__(self, name, data, *, read_only=False):
self.name = name
self.data = data
self.read_only = read_only
def set_value(self, coord, value, *, internal=False):
if self.read_only and not internal:
raise AttributeError(
f"Property '{self.name}' is read-only."
)
self.data[coord] = value
All writes go through set_value. Read-only enforcement lives here.
2. PropertyDescriptor: expose view only
class PropertyDescriptor:
def __init__(self, layer: PropertyLayer):
self.layer = layer
def __get__(self, instance: Cell, owner):
return self.layer.data[instance.coordinate]
def __set__(self, instance: Cell, value):
raise AttributeError(
f"Property '{self.layer.name}' is read-only."
)
Descriptors never mutate state. One descriptor per property.
3. HasPropertyLayers: support read-only layers
class HasPropertyLayers:
def add_property_layer(self, layer: PropertyLayer):
self._mesa_property_layers[layer.name] = layer
setattr(self.cell_klass, layer.name, PropertyDescriptor(layer))
No special-case wiring required.
4. Grid / Space internals update managed layers explicitly
Where agent changes affect managed properties:
self.property_layers["empty"].set_value(
cell.coordinate,
False,
internal=True
)
Same for removal or other derived properties.
Result
cell.empty = Falseraises immediatelycell.emptyremains readable and backward compatible- All managed invariants are protected
- Any property layer can be made read-only generically
- Cell remains completely unaware of property storage
@kevin-joshua That is an interesting approach, but making PropertyDescriptor always read-only breaks the ability to have standard writable property layers (e.g., cell.temperature = 10), which we still need.
@quaquel
I propose a simpler, higher-performance solution that supports both cases without overhead:
-
Keep the Descriptor Flexible: We simply add a
read_onlyflag to the existingPropertyDescriptor.- If
read_only=False(default): Standard__set__behavior. - If
read_only=True:__set__raisesAttributeError. This avoids forcing a "setter" API on everything.
- If
-
Direct Data Access for Internals: For internal updates (like
Gridmanagingempty), we don't need aset_value(..., internal=True)method. We should just access the data structure directly:layer.data[coord] = value.- Benefit: This removes the function call overhead for every agent move, keeping the simulation fast.
-
Zero-Cost Cell Fallback: We define
Cell.emptyas a standard@property(returninglen(agents)==0). When the Grid initializes a read-only "empty" layer, it simply overwrites this property on the class/instance.- Benefit:
Cellremains completely decoupled and works perfectly inNetworkor standalone tests.
- Benefit:
Hi @Nithin9585, I believe there are some architectural flaws in your proposal:
Direct Data Access for Internals: For internal updates (like Grid managing empty), we don't need a set_value method. We should just access the data structure directly: layer.data[coord] = value.
This update happens inside Cell.add_agent(). The Cell class does not know that layer.data exists. It doesn't have a reference to the PropertyLayer. To make this line of code (layer.data[coord] = value) work inside Cell.add_agent, you would have to give the Cell a reference to the layer. That creates Tight Coupling, which is exactly what we are trying to avoid.
When the Grid initializes a read-only "empty" layer, it simply overwrites this property on the class/instance
The Grid overwrites cell.empty with the Read-Only Descriptor (which reads from NumPy).
You call cell.add_agent(). It adds an agent to the _agents list, because you removed the "Setter API", nothing updates the NumPy array.
The Result:
cell.agentshas 1 agent.layer.data[coord]still says True (Empty).
Bug: cell.empty returns True (because it reads NumPy), but the cell actually contains an agent.
Also @quaquel mentioned
I prefer 2 descriptors over a single one with an if-statement in it.
Based on #3080 and my pathfinding in #3113, I am inclined to make cell.empty, and its link to an underlying numpy array part of the generic DiscreteSpace class. This also means that any work we do on DiscreteSpace.select_random_empty_cell() and DiscreteSpace.empties can rely on DiscreteSpace._empty.
However, implementing this change will be backward incompatible, or a bit tricky to do in a backward-compatible manner. In grids, Cell.empty is just a view into Grid.empty.data[cell.coordinate].
Currently, the coordinate of a cell in NetworkGrid is derived from the node ID in the underlying networkx graph. This already gives rise to problems (see #3045 and #3065). Something similar holds for VoronoiGrid, where the coordinate is taken from the centroids of the Voronoi patches. However, it also means that if we want to move the Grid.empty functionality to DiscreteSpace, we need a Mesa-controlled way of specifying the coordinate, since it must map to a cell in a NumPy array.
An additional advantage of taking explicit control over how Cell.coordinate is determined is that all property layer components can also benefit from it and thus can work with NetworkGrid and VoronoiGrid.
@EwoutH, I would appreciate your thoughts on this direction.
Seems like a proper direction to explore. I don't mind an API break here, if we can neatly deprecate the current behavior we do that and otherwise we're bumping to Mesa 4 anyways.
I was thinking, might need to have two kinds of property structures in the future:
- A property layer, which has distinctly structured cells that directly map to coordinates
- A property array, which directly map to cell/node IDs
In a grid they are basically identical, but in a network or irregular cell space (like Voronoi), you might want fast property acces both by the coordinate (like an agent position) and the cell number/id.
So maybe we have general property access that binds to a (continuous) space/coordinate system, and cell-based property access that binds to a discrete space and their internal cell numbering.
It might be possible to do it in a backward compatibility manner. Basically, we need a distinction between a unique identifier/index, and the position/coordinate. For grids, they can be the same. For Voronoi and networks, they are different. We can simply add the identifier as an extra argument and move HasProperties to DiscreteSpace, where it uses the new identifier instead of Cell.coordinate.
For Mesa 4, we can then improve on this by using the coordinate/position consistently in all plotting (avoiding the network bugs that are open PRs at the moment).