# Magic (Dunder) Methods & Protocols

> Master Python special double-underscore methods: __str__ versus __repr__, __len__, comparison dunders like __eq__, and operator overloading protocols.

Subject: Python | Lesson 15 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/magic-methods
Previous: [Inheritance, Polymorphism & super()](https://codewithanimation.in/python/inheritance.md) | Next: [Modules, Imports & the __main__ Guard](https://codewithanimation.in/python/imports.md)

## Hooking into Python Core Syntax Protocols

In Python, magic methods (also known as dunder methods because they begin and end with double underscores, like `__init__`) are special hooks that allow custom classes to integrate seamlessly with Python's built-in operators and functions.

Whenever you call `len(my_obj)`, Python does not read a private property directly; it translates your call into `my_obj.__len__()`.

Similarly, evaluating `a + b` invokes `a.__add__(b)`, and checking `a == b` invokes `a.__eq__(b)`. By implementing these standard methods, your custom objects behave like native Python types.

## __str__ vs __repr__: The String Representations

Python provides two distinct ways to convert an object into a string:

1. `__str__` is intended to be readable and user-friendly. It is called by `str(obj)` and `print(obj)` to present a clean summary for end-users.

2. `__repr__` is intended to be unambiguous and developer-focused. It is called by `repr(obj)`, interactive REPLs, and when objects are printed inside collections like lists or dictionaries.

An ideal `__repr__` returns a valid Python expression string that could recreate the exact object (for example, `Point(x=10, y=20)`).

## The Container and Comparison Protocols

Container protocols: implementing `__len__(self)` allows your object to answer `len(obj)`. Implementing `__getitem__(self, key)` enables square-bracket indexing `obj[key]`, and `__contains__(self, item)` powers the `item in obj` membership check.

Comparison protocols: by default, custom class instances compare equality by their memory address (identity). Implementing `__eq__(self, other)` enables custom value-based equality checking with `==`.

Implementing `__lt__(self, other)` enables the `<` operator, which allows instances of your class to be sorted naturally using Python's built-in `sorted(my_objects)`.

## Common mistake: Defining __str__ Without __repr__

A frequent oversight is implementing `__str__` while forgetting to implement `__repr__`.

If you only implement `__str__`, calling `print(point)` displays your pretty string. But if you print a list containing that object `print([point])`, Python uses `__repr__` to display list items, resulting in ugly unreadable output like `[<__main__.Point object at 0x7fa0>]`.

Rule of thumb: always implement `__repr__` first. If a class defines `__repr__` but no `__str__`, Python automatically falls back to `__repr__` for `str()` calls.

## Tip: Use dataclasses to Auto-Generate Dunders

Python 3.7+ includes the `@dataclass` decorator in the standard library: `from dataclasses import dataclass`. Applying `@dataclass` to a class automatically writes clean, tested `__init__`, `__repr__`, and `__eq__` methods based on type-annotated fields, saving dozens of boilerplate lines.

## Try it: The Operator-to-Dunder Translation Lab

Test built-in Python expressions like str(), repr(), len(), and equality == against a custom Vector class. Watch how Python translates every built-in operation into a corresponding dunder method call.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/magic-methods

## Check yourself

### Question 1

What does Python display when you execute `print([item])` if the class of `item` defines `__str__` but does not define `__repr__`?

- A. The default representation `<ClassName object at 0x...>` because collections display items via __repr__
- B. The string returned by __str__
- C. TypeError: __repr__ required for list inclusion
- D. An empty string

Correct answer: A

Collections (lists, tuples, dicts, sets) call `repr()` on their elements rather than `str()`. Without a custom `__repr__`, the default memory pointer is printed.

- Why not B: Containers like lists and dicts always format their contents using __repr__, never __str__.
- Why not C: Python does not crash; it falls back to the default object __repr__.
- Why not D: Python produces the default memory address string.

### Question 2

Which magic method must be implemented to allow instances of a class to be used with the `len()` built-in function?

- A. __len__
- B. __length__
- C. __size__
- D. __count__

Correct answer: A

Calling `len(obj)` invokes `obj.__len__()`. It must return a non-negative integer, or Python raises a TypeError.

- Why not B: __length__ is not a Python dunder method.
- Why not C: __size__ is not the dunder hook for len().
- Why not D: __count__ is not a valid container protocol hook.

### Question 3

What does Python's `==` comparison operator evaluate by default on custom classes if `__eq__` is not defined?

- A. Identity comparison (memory address equality `is`)
- B. A shallow comparison of all instance attributes
- C. Alphabetical comparison of the class name
- D. TypeError: equality not supported

Correct answer: A

By default, objects inherit `object.__eq__`, which evaluates identity (`self is other`). Implementing `__eq__` enables value-based equality.

- Why not B: Python does not compare attribute dictionaries unless __eq__ is implemented or provided by @dataclass.
- Why not C: Python compares object identity, not class names.
- Why not D: Python defaults to identity comparison rather than raising an error.

## Remember this

- Dunder methods allow custom classes to hook into Python syntax and built-in operators.
- __repr__ is for developers and debugging; __str__ is for clean user-facing string representations.
- Always define __repr__ first; Python falls back to __repr__ if __str__ is missing.
- __len__ enables len(), __getitem__ enables indexing [key], and __eq__ enables == comparison.
- Use @dataclass to eliminate repetitive manual dunder method boilerplate.
