Skip to content

Added __repr__ method to Agent class - #3759

Merged
quaquel merged 14 commits into
mesa:mainfrom
dietcoke-17:missing-repr-in-agent
Jul 18, 2026
Merged

quaquel merged 14 commits into
mesa:mainfrom
dietcoke-17:missing-repr-in-agent

Conversation

@dietcoke-17

Copy link
Copy Markdown
Contributor

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread mesa/agent.py Resolved
@github-actions

Copy link
Copy Markdown

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%]

Comment thread mesa/agent.py Outdated
Comment on lines +213 to +215
"""Return an unambiguous string representation of the agent."""
return f"{self.__class__.__name__}(unique_id={self.unique_id})"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?

@dietcoke-17

Copy link
Copy Markdown
Contributor Author

@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.

@EwoutH

EwoutH commented Jun 25, 2026

Copy link
Copy Markdown
Member

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.

@quaquel

quaquel commented Jun 25, 2026

Copy link
Copy Markdown
Member

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.

@dietcoke-17

Copy link
Copy Markdown
Contributor Author

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.

@dietcoke-17

Copy link
Copy Markdown
Contributor Author

@EwoutH @quaquel should i go with repr and make changes in the pr according to that or should we stick to our str?

@quaquel

quaquel commented Jun 30, 2026

Copy link
Copy Markdown
Member

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.

@dietcoke-17

Copy link
Copy Markdown
Contributor Author

Thank You @quaquel

@dietcoke-17

dietcoke-17 commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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.

@dietcoke-17 dietcoke-17 reopened this Jul 1, 2026
@quaquel

quaquel commented Jul 1, 2026

Copy link
Copy Markdown
Member

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.

@dietcoke-17

Copy link
Copy Markdown
Contributor Author

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) # →
str(wolf) # → Wolf, agent_id = 0

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 format (consistent with AgentSet)

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) # → ✅
str(wolf) # → Wolf, agent_id = 0 ✅

Comment thread mesa/agent.py Outdated
def __repr__(self) -> str:
"""Return an unambiguous string representation including agent state."""
# Mesa default fields to exclude
mesa_fields = {"model", "unique_id", "current_action"}

@quaquel quaquel Jul 16, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread mesa/agent.py

# Build the repr string
if user_attrs:
attr_str = ", ".join(f"{k}={v!r}" for k, v in user_attrs.items())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what does `!r! do?

@dietcoke-17 dietcoke-17 Jul 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 quaquel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks fine but I have some clarifying questions and a minor suggestion.

@dietcoke-17

Copy link
Copy Markdown
Contributor Author

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

@quaquel quaquel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks

@quaquel quaquel added the enhancement Release notes label label Jul 18, 2026
@quaquel
quaquel merged commit 3fafc76 into mesa:main Jul 18, 2026
10 of 11 checks passed
@dietcoke-17
dietcoke-17 deleted the missing-repr-in-agent branch July 18, 2026 15:17
EwoutH pushed a commit that referenced this pull request Oct 28, 2026
@EwoutH EwoutH mentioned this pull request Nov 15, 2026
53 of 65 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Agent is missing __repr__ inconsistent with every other core Mesa class

3 participants