Repository navigation
Added __repr__ method to Agent class - #3759
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4c39a80de4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Performance benchmarks:
|
| """Return an unambiguous string representation of the agent.""" | ||
| return f"{self.__class__.__name__}(unique_id={self.unique_id})" | ||
|
|
There was a problem hiding this comment.
I am not sure about this. It suggests that you can initialize the agent with unique_id which is not correct at all.
Also, more broadly, should we not add these to all agent classes in mesa (so cell agent shows the cell field as well)?
|
@quaquel Thanks for the feedback! quick clarifications required: On the format: What format would be clearer? which should i prefer:
Broader scope: |
|
Thanks for the PR. I think it's worth checking whether |
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 For This is the same approach Mesa used for SolaraViz and AgentSet one good API that serves both audiences, not duplication. |
|
I like it when |
|
Thank You @quaquel |
|
I want to clarify your suggestion about "clever parsing of dict". You said 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 |
|
This implements
Keeps Example output: Implemented smart approach — Auto-parse -Filters out Mesa internal fields (model, unique_id, current_action) what changed in which file Added tests/test_agent.py: Added test_agent_repr() — tests repr with custom attributes Before:repr(wolf) # → <mesa.agent.Wolf object at 0x7f3b2c1d4a90> ❌ After:repr(wolf) # → ✅ |
| def __repr__(self) -> str: | ||
| """Return an unambiguous string representation including agent state.""" | ||
| # Mesa default fields to exclude | ||
| mesa_fields = {"model", "unique_id", "current_action"} |
There was a problem hiding this comment.
We now hard code these fields in this method. Is there a more generic, potentially user extendable way of handling this?
Also, I would always include unique_id, so I suggest removing it from this set.
|
|
||
| # Build the repr string | ||
| if user_attrs: | ||
| attr_str = ", ".join(f"{k}={v!r}" for k, v in user_attrs.items()) |
There was a problem hiding this comment.
The !r calls repr() on the value. It ensures strings are quoted and also
f"wealth={wealth}, name={name}"
→ "wealth=100, name=wolf" --here name looks like code
but
f"wealth={wealth!r}, name={name!r}"
→ "wealth=100, name='wolf'" --string is quoted
It also ensures that when someone reads the repr output, they immediately understand:
-What type each value is
-Whether it's a string, number, None, etc.
-No ambiguity
quaquel
left a comment
There was a problem hiding this comment.
It looks fine but I have some clarifying questions and a minor suggestion.
|
Added comprehensive coverage tests for repr filtering logic
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 |
(cherry picked from commit 3fafc76)
Summary
Adds
__repr__method to theAgentclass to provide meaningful string representations in debuggers, logs, and interactive shells.Problem
The
Agentclass defined__str__but not__repr__, causingrepr(agent)to fall back toobject.__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