Question presented to candidate:
"When Python evaluates a + b, what actually happens? Which object's method gets called, what happens if it does not know how to add the other type, and how is a += b different?"
What a strong answer should cover:
a + bcallstype(a).__add__(a, b); if that is missing or returnsNotImplemented, Python callstype(b).__radd__(b, a); if that also fails,TypeError: unsupported operand type(s) for +.NotImplementedis a special value to return (notNotImplementedErrorto raise), meaning "I cannot handle this type, ask the other side".- The subclass rule: if
type(b)is a subclass oftype(a)and overrides__radd__,b.__radd__is tried first; if both operands have the same type,__radd__is never tried. - Methods are looked up on the type, not the instance, so patching
obj.__add__has no effect onobj + x. a += btries__iadd__first (in-place, e.g.listmutates and aliases see it), falling back toa = a + b(e.g.tuple,int,str); thet[0] += [x]tuple gotcha.- CPython detail: since 3.11 all binary operators compile to a single
BINARY_OPinstruction with the operator in its argument.
Code / implementation expected: Optional β a small class with __add__ and __radd__ returning NotImplemented for unsupported types.