In the first example, you didn't apply the +=
operator to the dictionary. You applied it to the value stored in the d['a']
key, and that's a different object altogether.
In other words, Python will retrieve d['m']
(a __getitem__
call), apply the +=
operator to that, then set the result of that expression back to d['m']
(the __setitem__
call).
The __iadd__
method either returns self
mutated in-place, or a new object, but Python cannot know for sure what the method returned. So it has to call d.__setitem__('m', <return_value_from_d['m'].__iadd__(1)>)
, always.
The exact same thing happens if you did:
m = d['m']
m += 1
d['m'] = m
but without the extra name m
in the global namespace.
If the mutable()
instance was not stored in a dictionary but in the global namespace instead, the exact same sequence of events takes place, but directly on the globals()
dictionary, and you wouldn't get to see the __getitem__
and __setitem__
calls.
This is documented under the augmented assignment reference documentation:
An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target.
where d['m']
is the target; evaluating the target here involves __getitem__
, assigning the result back to the original target invokes __setitem__
.