Added __repr__ method to Agent class
Summary
Adds __repr__ method to the Agent class to provide meaningful string representations in debuggers, logs, and interactive shells.
Problem
The Agent class defined __str__ but not __repr__, causing repr(agent) to fall back to object.__repr__ which returns an unhelpful memory address that changes every run. This makes agents invisible in debuggers and logging output.
Solution
Implemented __repr__ to return a descriptive string following the format: ClassName(unique_id=<value>)
Consistency This change brings Agent in line with other core Mesa classes (EventList, Model, etc.) which already define repr. The pattern established in PR #2195 is now applied to Agent.
Testing Added three new tests to verify:
test_agent_str(): Validates the existing str method test_agent_repr(): Validates the new repr method test_agent_repr_subclass(): Ensures repr correctly uses the subclass name (e.g., Wolf not Agent)
Fixes Closes #3758
Performance benchmarks:
| Model | Size | Init time [95% CI] | Run time [95% CI] |
|---|---|---|---|
| BoltzmannWealth | small | 🟢 -7.1% [-8.3%, -5.8%] | 🟢 -4.4% [-4.6%, -4.1%] |
| BoltzmannWealth | large | 🔵 +0.3% [-0.3%, +0.9%] | 🔵 +3.5% [+1.9%, +5.1%] |
| Schelling | small | 🔵 -1.2% [-1.9%, -0.5%] | 🔵 -0.0% [-0.8%, +0.8%] |
| Schelling | large | 🔵 +0.6% [+0.0%, +1.4%] | 🔵 -2.1% [-3.9%, -0.2%] |
| WolfSheep | small | 🔵 -1.6% [-2.3%, -0.8%] | 🔵 -2.6% [-6.6%, +1.8%] |
| WolfSheep | large | 🔵 +2.8% [+1.2%, +4.3%] | 🔵 +3.3% [+0.0%, +6.2%] |
| SugarscapeG1mt | small | 🔴 +5.2% [+4.4%, +6.1%] | 🔵 -0.4% [-1.8%, +1.1%] |
| SugarscapeG1mt | large | 🔴 +5.8% [+3.9%, +8.3%] | 🔵 +0.5% [-1.1%, +2.3%] |
| BoidFlockers | small | 🔴 +4.3% [+3.4%, +5.1%] | 🔵 -0.2% [-0.6%, +0.1%] |
| BoidFlockers | large | 🔵 +1.0% [+0.1%, +1.8%] | 🔵 -0.0% [-0.2%, +0.2%] |
@quaquel Thanks for the feedback! quick clarifications required:
On the format:
You're right — Agent(unique_id=0) is misleading because unique_id can't actually be passed to __init__.
What format would be clearer? which should i prefer:
Agent[id=0](brackets instead of parens to signal it's not a constructor)<Agent id=0>(angle brackets, like AgentSet)Agent@0(symbol notation)- Something else would be better
Broader scope:
You're right — we should add __repr__ to all agent classes consistently, not just Agent. Should I expand this PR to include CellAgent (show cell field) or separtely we would adress this in another PR which would be easier for you i will move in that direction.
Thanks for the PR.
I think it's worth checking whether __str__ and __repr__ should return (meaningfully) different things here. A common practice is to define only __repr__ unless you need a distinct human-friendly format. Since str() falls back to __repr__ anyway, one method covers both. If they're returning essentially the same info, dropping __str__ and keeping just __repr__ would be cleaner.
What format would be clearer? which should i prefer:
I would stay close to agentset, but @EwoutH does raise a relevant point as well. So curious to hear your thoughts on this.
Thanks @EwoutH @quaquel for the query Looking at Mesa's design philosophy from contributing.md and the JOSS paper, what i had the picture on my mind that mesa is designed to serve both beginner and advanced programmers with one clean API, not separate ones.
For __str__ vs __repr__, I propose we follow that principle:
I think we should drop __str__, keep only __repr__** and why due to the following consideration from my side:-
1.Beginners can see clear, context-rich output
2.Developers will see unambiguous, searchable output
3.One method, two use cases consistent with Mesa's philosophy of unified APIs
4.Follows Python best practice that Ewouth sir has already mentioned that str() naturally falls back to __repr__
This is the same approach Mesa used for SolaraViz and AgentSet one good API that serves both audiences, not duplication.
@EwoutH @quaquel should i go with repr and make changes in the pr according to that or should we stick to our str?
I like it when str returns a human readable string while repr is more technical. For something like Agent that might be overkill unless repr does some clever parsing of __dict__ so you get more insight into the state of the agent. Hope this helps.
Thank You @quaquel
I want to clarify your suggestion about "clever parsing of dict".
You said __repr__ might be worth doing if it shows more insight into the agent's state. I have three options:
Option A: Just unique_id (current PR)
repr(wolf) # → Wolf(unique_id=0)
Simple, but not much state info.
Option B: Show all agent attributes from dict
repr(wolf) # → <Wolf id=0 wealth=100 energy=50 state='active'>
Shows full agent state. Flexible across subclasses.
Option C: Make it base implementation + override-friendly
# Base class shows just id:
repr(agent) # → <Agent id=0>
# Subclasses can override to show their fields:
class Wolf(Agent):
def __repr__(self):
return f"<Wolf id={self.unique_id} wealth={self.wealth}>"
repr(wolf) # → <Wolf id=0 wealth=100>
Gives subclasses control over what to show.
Which direction makes sense? And should this apply to all agent classes (Agent, CellAgent, etc.) or start with Agent and iterate?
I want to make sure this is worth the complexity before implementing.
What I had in mind is a bit different. Your idea forces the user to implement a dunder method to get useful information. However, we can already handle this by including __dict__ inside how we implement __repr__. We just need to filter out any default mesa fields and probably anything with a leading underscore.
This implements __repr__ method that automatically shows user-defined attributes by parsing __ dict __ filtered to exclude:
- Mesa internal fields (model, unique_id, current_action)
- Private attributes (starting with _)
Keeps __str__ unchanged for human-readable output.
No user override needed; works automatically for all Agent subclasses.
Example output:
repr(wolf) # →
Implemented smart approach — Auto-parse __dict__ to show user-defined attributes:
-Filters out Mesa internal fields (model, unique_id, current_action) -Filters out private attributes (starting with _) -No user override needed — works automatically for all sub-classes
what changed in which file mesa/agent.py:
Added __repr__ method below existing __str__
Shows class name, id, and all custom attributes
Uses angle brackets
tests/test_agent.py:
Added test_agent_repr() — tests repr with custom attributes Added test_agent_repr_basic() — tests repr with no custom attributes Added test_agent_repr_subclass() — tests subclass name appears correctly
class Wolf(Agent):
def __init__(self, model):
super().__init__(model)
self.wealth = 100
self.energy = 50
wolf = Wolf(model)
Before:
repr(wolf) # → <mesa.agent.Wolf object at 0x7f3b2c1d4a90> ❌
After:
repr(wolf) # →
Added comprehensive coverage tests for repr filtering logic
- Tests filtering of Mesa internal fields (model, current_action)
- Tests filtering of private attributes (starting with _)
- Tests repr formatting with various types (strings, numbers, None, lists)
Also while adding new test found out that there are some missing test needed to be added in the agent which will increse the overall codecove score overall