Special Methods (Dunder) Intro
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
NotImplementedfor unsupported comparisons.
Failure Modes
- Bad repr: logs become useless during incidents.
- Wrong equality: cache keys and dedupe logic break silently.