Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Objects with purpose
EXPERIMENT 47 / 101

Make your object feel native.

Support len, membership, and iteration with a small, deliberate protocol.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

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.

python_protocols.py
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))
↳ EXPECTED OUTPUT
2
True
['Build', 'Test']

03 Under the hood

  1. 1

    Copying the iterable into a list avoids directly sharing the caller’s list, although nested mutable elements would still be shared.

  2. 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. 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

A SMALL MISSION

Add a readable string representation to a small Task object.

Reveal one possible solution +
one_possible_solution.py
class Task:
    def __init__(self, name): self.name = name
    def __str__(self): return f"Task<{self.name}>"
print(Task("Build"))

05 Check your signal

QUICK SIGNAL CHECK

What should __iter__ return?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.