Moving an unplaced agent in discrete space raises raw AttributeError instead of ValueError
Pre-PR Checklist
- [x] This is a bug report, not a feature request or discussion.
Summary
Attempting to move an unplaced moving agent (CellAgent, Grid2DMovingAgent, or HexGridMovingAgent) crashes with a raw AttributeError: 'NoneType' object has no attribute 'connections' (or 'coordinate') rather than raising a clean, informative ValueError.
Bug / Issue
In #3748 / PR #3986, FixedAgent was updated to properly handle being unplaced, raising a clean ValueError if an unplaced agent is operated on (FixedAgent.remove()):
if self.cell is None:
raise ValueError(
f"Cannot remove {type(self).__name__} {self.unique_id}: it is not "
"in a cell. A fixed agent has to be placed in a cell before it "
"can be removed."
)
However, unplaced mobile agents (CellAgent, Grid2DMovingAgent, and HexGridMovingAgent) were left unhandled when attempting relative movement:
- In
BasicMovement.move_relative(direction)(mesa/discrete_space/cell_agent.py:70):new_cell = self.cell.connections.get(direction)Whenself.cell is None, this crashes with:AttributeError: 'NoneType' object has no attribute 'connections' - In
HexGridMovingAgent.move(direction)(mesa/discrete_space/cell_agent.py:231):row_index = self.cell.coordinate[1]Whenself.cell is None, this crashes with:AttributeError: 'NoneType' object has no attribute 'coordinate'
An unplaced agent cannot move relative to its current cell since it has no cell. Attempting to do so should raise a clear ValueError before attempting to access cell attributes.
Expected Behavior
Calling move_relative() or move() on an unplaced agent should raise a descriptive ValueError:
ValueError: Cannot move CellAgent 1: it is not in a cell. An agent must be placed in a cell before it can move.
Steps to Reproduce
import mesa
from mesa.discrete_space import CellAgent, Grid2DMovingAgent, HexGridMovingAgent
model = mesa.Model()
# 1. CellAgent
agent1 = CellAgent(model)
agent1.move_relative((1, 0))
# AttributeError: 'NoneType' object has no attribute 'connections'
# 2. Grid2DMovingAgent
agent2 = Grid2DMovingAgent(model)
agent2.move("north")
# AttributeError: 'NoneType' object has no attribute 'connections'
# 3. HexGridMovingAgent
agent3 = HexGridMovingAgent(model)
agent3.move("nw")
# AttributeError: 'NoneType' object has no attribute 'coordinate'
Proposed Fix
In BasicMovement.move_relative(), Grid2DMovingAgent.move(), and HexGridMovingAgent.move(), check whether self.cell is None and raise a clear ValueError following the exact pattern from #3986.
As indicated in the PR I closed, a Value error is not appropriate here. The ValueError exception occurs if a function receives a value of wrong type. But the methods in question don't receive any value and so should never raise a value error.
This also applies to FixedAgent.remove() from #3986. It raises a ValueError for an unplaced agent, and remove() doesn't receive a value either. So whatever type is chosen here should probably go there too, so both "agent has no cell" cases raise the same thing.
mesa/exceptions.py has SpaceException for discrete space errors, but nothing for this case yet. Something like an AgentNotPlacedException(SpaceException) could cover both moving and removing an unplaced agent. Happy to switch FixedAgent.remove() over once the type is settled. cc @Dilraj07
Thanks for pointing that out @quaquel, looking at standard Python exception semantics, you're completely right. This is an invalid agent/space state (the agent is not attached to a cell) rather than an invalid parameter value, so ValueError is the wrong abstraction here.
Looking into mesa/exceptions.py, discrete space errors already follow a domain-specific hierarchy under SpaceException (CellFullException, CellMissingException, etc.).
I like @AshNicolus's point regarding FixedAgent.remove() from #3986. Both move_relative() and remove() represent the exact same precondition failure: an operation requiring cell placement was attempted on an unplaced agent.
Introducing a dedicated AgentNotPlacedException(SpaceException) in mesa/exceptions.py seems like the cleanest and most cohesive fit. It could accept the agent and an optional action (e.g. action="move" or action="remove") so it produces clean contextual messages like:
Cannot move CellAgent 1: it is not in a cell.Cannot remove FixedAgent 1: it is not in a cell.
What are your thoughts on this naming and hierarchy under SpaceException?
Do we need to refine the exception hierarchy? I think a SpaceException with the descriptive error message should be sufficient.
7. Do we need to refine the exception hierarchy? I think a SpaceException with the descriptive error message should be sufficient.
Agreed @quaquel, using SpaceException with a descriptive message works well. SpaceException already serves as the base for discrete space errors, and the message provides clear context on what went wrong.
What we can do is use SpaceException consistently for unplaced agent operations:
- In
move_relative()(and the grid agentmove()methods): raiseSpaceExceptionwhenself.cell is None. - In
FixedAgent.remove(): align theValueErrorfrom #3986 toSpaceExceptionas well, so all operations requiring an agent to be in a cell raise the same exception type.
Agreed, SpaceException with a clear message is enough, no need for a new type.
@Dilraj07 go ahead and switch FixedAgent.remove() over in your PR, so both cases change together and we avoid two PRs touching the same tests. Happy to review it when it is up.