mesa icon indicating copy to clipboard operation
mesa copied to clipboard

feat: Add __str__() to Agent and other Base classes

Open IlamaranMagesh opened this issue 8 months ago • 13 comments

What's the problem this feature will solve?

Agent and most base classes don't have a __str__ method. This makes a huge difference as Agent is now inherited by different types of subclasses (cell, fixed, meta-agent, llm-agent (has its own __str__), etc.) Having a template pattern for __str__ will help identify and increase readability. Right now the agents are identified in logging and debugging by their unique_id with manually having to type subAgent.__class__.__name__

Current usage:

print(f"{agent.unique_id} is called.")

# To know what agent it is one has to do
print(f"{agent.__class__.__name___}:{agent.unique_id} is called")
# or
print(f"{type(agent).__name___}:{agent.unique_id} is called")

After __str__:

print(f"{agent} is called")

Describe the solution you'd like

  1. To add __str__ to Agent and other base classes
  2. Use Template pattern to make sure one string structure is followed across the framework

Template Pattern

class Agent:
    def __init__(self, unique_id):
        self.unique_id = unique_id
    
    def _get_extra_info(self):
        """Hook for subclasses to add extra identifying info."""
        return ""

    def __str__(self):
        extra = self._get_extra_info() # "[CellAgent]"
        return f"<{self.__class__.__name__} {extra} ID:{self.unique_id}>" # "Agent [CellAgent] ID: 1"

class CellAgent (Agent):
    def __init__(self, team):
        self.team = team

    def _get_extra_info(self):
        # We just provide the data; the Base Agent handles the brackets and format
        return f"[CellAgent]"

Similarly for other base classes. I would like to know your thoughts on this.

Alternate implementation would be having the string augmented by subclasses themselves, which in my opinion harder to maintain and easy to corrupt the structure.

Are you planning to open a PR for this?

Yes, upon aligning with maintainers and if this is aligned, the next step would be to add __repr__ for debugging.

IlamaranMagesh avatar Mar 23 '26 18:03 IlamaranMagesh

Hi @EwoutH and @IlamaranMagesh,

I've been looking at this issue and implemented a simpler version of __str__ and __repr__ for the Agent base class:

def __str__(self) -> str:
    return f"<{self.__class__.__name__} ID:{self.unique_id}>"

def __repr__(self) -> str:
    return f"{self.__class__.__name__}(unique_id={self.unique_id}, model={self.model})"

I skipped the _get_extra_info() hook for now to keep it minimal — happy to add it if maintainers prefer the template pattern approach.

Would love to open a PR if this direction is aligned. Let me know!

Atharva76-cpu avatar Mar 28 '26 13:03 Atharva76-cpu

Hey, I added _get_extra_info() to get the subclass Agent name. Since there might be multiple agents, it's best to know what agent it is in my opinion, but I'd like to hear your thoughts on the design choice. I wanted to align with the maintainers, exactly for this reason before opening a PR. It's best to discuss and finalise the implementation as this is will be a template for all the subclasses.

IlamaranMagesh avatar Mar 28 '26 19:03 IlamaranMagesh

  1. Adding __str__ makes sense, but with __repr__ the idea is that the string should be adequate for recreating the instance, so your version fails this purpose. \
  2. I have no idea what you try to achieve with extra info. You can access self.__dict__, so you have in principle everything you need.

quaquel avatar Mar 28 '26 19:03 quaquel

  1. Adding __str__ makes sense, but with __repr__ the idea is that the string should be adequate for recreating the instance, so your version fails this purpose. \

Agree, the idea I proposed is only for __str__

  1. I have no idea what you try to achieve with extra info. You can access self.__dict__, so you have in principle everything you need.

We don't have a __str__ implementation yet, so I thought of giving options for a template. This is to get a verbose custom string implemented in the subclasses but again it is purely based on the template we decide for __str__. If the template is as simple as only the class names, we can ignore that hook.

IlamaranMagesh avatar Mar 28 '26 19:03 IlamaranMagesh

Great points from both sides!

@IlamaranMagesh — the _get_extra_info() hook idea is actually smart for maintaining a consistent template across subclasses. But as @quaquel pointed out, since self.dict already exposes everything, the hook adds complexity without much benefit. Subclasses can simply override str directly when needed — same result, less overhead.

@quaquel — agreed on keeping it simple:

def str(self) -> str: return f"<{self.class.name} ID:{self.unique_id}>"

This covers the base case cleanly. Subclasses can always override str if they need extra info — no hook required.

Thoughts??

Atharva76-cpu avatar Mar 29 '26 06:03 Atharva76-cpu

Subclasses can simply override str directly when needed — same result, less overhead.

Usually, people avoid overriding __str__. It comes with a trade off, maintability. The template pattern enforces a template to follow by the subclasses and also when you need to update the __str__ template, you update only in the base class.

extra_info hook is given only if the __str__ is designed to be verbose, like a subclass adding custom string. It's completely optional based on the design choice.

IlamaranMagesh avatar Mar 29 '26 16:03 IlamaranMagesh

@IlamaranMagesh — agreed that overriding __str__ entirely in subclasses is the weaker pattern from a maintainability standpoint. Your concern is valid.

That said, I think the decision comes down to one question for @quaquel: is format consistency across subclasses a hard requirement for this codebase?

  • If yes → the hook pattern is worth the extra abstraction
  • If no → the simple __str__ + per-subclass override is sufficient

One middle ground either way: start with the simple __str__ now, and introduce _get_extra_info() only when a subclass actually needs custom output. Avoids premature abstraction while keeping the door open.

class Agent:
    def __str__(self) -> str:
        return f"<{self.__class__.__name__} ID:{self.unique_id}>"

Atharva76-cpu avatar Mar 29 '26 16:03 Atharva76-cpu

I don't see a lot of value in developing a generic structure for __str__ that users can rely on. If they want to control it, it is easier for them to just overwrite the implementation. In general, the agent subclass and agent_id should be generically useful and sufficient in many cases.

Another minor point: __str__ should be useable for a human so, I don't see value in adding < ... > Just have the class name and the agent id, probably comma seperated and with a tag should be sufficient.

quaquel avatar Mar 29 '26 17:03 quaquel

Okay, will open up a PR to address this

IlamaranMagesh avatar Mar 29 '26 17:03 IlamaranMagesh

@quaquel — thanks for actively sharing your thoughts!

Agreed on keeping it simple. One thing worth pinning down — you mentioned "with a tag should be sufficient". I'd propose something like:

def __str__(self) -> str:
    return f"[{self.__class__.__name__}] id={self.unique_id}"

The [ClassName] bracket acts as a lightweight tag that makes log lines scannable at a glance, without the overhead of the full < ... > wrapping. Easier to grep and visually distinct from plain text.

Does that match what you had in mind, or would a different format work better?

Atharva76-cpu avatar Mar 29 '26 17:03 Atharva76-cpu

I was thinking more along the lines of

f"{self.__class__.__name__}, agent_id = {self.unique_id}"

but I am open to other ideas. The main thing is that it should be designed to be human-readable first.

quaquel avatar Mar 29 '26 17:03 quaquel

@Atharva76-cpu, if you are interested, you can open up a PR. I don't want multiple resources spending time on the same implementation. Moreover, it avoids clutter for the maintainers. I can do a review though, once it's done and provide my feedback.

IlamaranMagesh avatar Mar 29 '26 17:03 IlamaranMagesh

@IlamaranMagesh — thanks for the opportunity! I'll open a PR with @quaquel's suggested format and keep the implementation minimal. Will tag you for review once it's up.

Atharva76-cpu avatar Mar 29 '26 19:03 Atharva76-cpu