PYTHON Contents

Special Methods (Dunder) Intro

Learn dunder methods to make objects behave predictably: string reprs, equality, ordering basics, and container-like behavior.

On this page

Why Dunder Methods Matter

Dunder methods define how your objects interact with Python: printing, comparisons, iteration, and more. Good implementations improve debugging and correctness.

repr vs str

class Job:
    def __init__(self, job_id: str) -> None:
        self.job_id = job_id

    def __repr__(self) -> str:
        return f"Job(job_id={self.job_id!r})"

    def __str__(self) -> str:
        return self.job_id

Equality

class User:
    def __init__(self, user_id: int) -> None:
        self.user_id = user_id

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, User):
            return NotImplemented
        return self.user_id == other.user_id

Operational Checklist

  • __repr__ should be unambiguous and useful for debugging.
  • Implement __eq__ carefully; consider hash behavior if objects go in sets/dicts.
  • Return NotImplemented for unsupported comparisons.

Failure Modes

  • Bad repr: logs become useless during incidents.
  • Wrong equality: cache keys and dedupe logic break silently.