Skip to content

Commit

Permalink
model.agents: Use a defaultdict of lists (instead of sets)
Browse files Browse the repository at this point in the history
lists keeps insertion order.
  • Loading branch information
EwoutH authored and tpike3 committed Dec 18, 2023
1 parent dc38f56 commit 09b3357
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions mesa/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ def __init__(self, unique_id: int, model: Model) -> None:
self.pos: Position | None = None

# Register the agent with the model using defaultdict
self.model.agents[type(self)].add(self)
self.model.agents[type(self)].append(self)

def remove(self) -> None:
"""Remove and delete the agent from the model."""
self.model.agents[type(self)].discard(self)
self.model.agents[type(self)].remove(self)

def step(self) -> None:
"""A single step of the agent."""
Expand Down
4 changes: 2 additions & 2 deletions mesa/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class Model:
running: A boolean indicating if the model should continue running.
schedule: An object to manage the order and execution of agent steps.
current_id: A counter for assigning unique IDs to agents.
agents: A defaultdict mapping each agent type to a set of its instances.
agents: A defaultdict mapping each agent type to a list of its instances.
"""

def __new__(cls, *args: Any, **kwargs: Any) -> Any:
Expand All @@ -50,7 +50,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
self.running = True
self.schedule = None
self.current_id = 0
self.agents: defaultdict[type, set] = defaultdict(set)
self.agents: defaultdict[type, list] = defaultdict(list)

@property
def agent_types(self) -> list:
Expand Down

0 comments on commit 09b3357

Please sign in to comment.