Make your object feel native.
Support len, membership, and iteration with a small, deliberate protocol.
01 The idea
Python’s built-ins call special methods to ask objects for standard behaviour. Implement __len__ for size, __iter__ for iteration, and __contains__ for membership when those ideas make sense for your class. Supporting a protocol is a commitment to expected semantics, not an opportunity to make ordinary syntax surprising.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
class Backlog:
def __init__(self, tasks): self._tasks = list(tasks)
def __len__(self): return len(self._tasks)
def __iter__(self): return iter(self._tasks)
def __contains__(self, task): return task in self._tasks
backlog = Backlog(["Build", "Test"])
print(len(backlog))
print("Build" in backlog)
print(list(backlog))2 True ['Build', 'Test']
03 Under the hood
- 1
Copying the iterable into a list avoids directly sharing the caller’s list, although nested mutable elements would still be shared.
- 2
__iter__ returns an iterator each time. Returning self would require implementing iterator state correctly and would usually make this container unexpectedly single-pass.
- 3
Keep special methods focused and cheap where users expect that. A __repr__ should aid debugging, while __str__ can provide a friendlier display.
04 Your turn, builder
Add a readable string representation to a small Task object.
Reveal one possible solution +
class Task:
def __init__(self, name): self.name = name
def __str__(self): return f"Task<{self.name}>"
print(Task("Build"))05 Check your signal
What should __iter__ return?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.