How does the “in” operator work in Python? – If an object defines __contains__, then its (boolean) result is returned (coerced to bool).– If not, then Python iterates over it with __iter__ Can you find and return a result faster than __iter__? Then define __contains__.
I really enjoy reading e-mail newsletters. They’re clever, informative, and funny, and provide me with lots of food for thought — as well as professional information that is crucial to my work. The thing is, I don’t have time to read them during the week. And on Saturday, when I do have time, I don’t…
In Python, we use “or” for conditions. | is bitwise (not boolean) “or”: x | y # 15, or 0b1111 | runs __or__. On dicts, | combines.
The % in Python, on numbers, is modulo: But str uses __mod__ for interpolation: Same operator, same magic method — but totally different.
Just as + in Python invokes __add__, other operators invoke other magic methods: • – is __sub__• * is __mul__• / is __truediv__• // is __floordiv__• % is __mod__• ** is __pow__ Your methods can do whatever you want. But do try to stick to conventional expectations.
I’ve been using Claude Code several hours a day for months, and I’m having a blast. But an agent does what you tell it, not what you meant — which is why validating your results now matters more than the results themselves.
If you tell Python it’ll run x.__add__(5), which handles the int 5. But what about int.__add__ doesn’t know how to handle x. So it returns NotImplemented — and Python turns it around, calling: That’s the “reverse add” magic method!
If your Python class implements __add__, it should usually return a new instance of your class, not an int:
How can your Python object support +? Implement __add__:
Operators in Python are turned into “magic” method calls: x + y # becomes x.__add__(y) So: Different errors from different methods!