It's mostly syntactic sugar, but not for the statements you list; instead, it's equivalent to
value = type(self)()
self[key] = value
To see the difference, type the following at your Python prompt:
>>> class FakeDict(object):
... def __setitem__(self, k, v):
... pass
... def __getitem__(self, k):
... raise KeyError("boom!")
...
>>> d = FakeDict()
>>> x = d[1] = 42
>>> d[1] = 42
>>> x = d[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in __getitem__
KeyError: boom!
Of course, with a well-behaved dict
, this won't matter, but
self[key] = type(self)()
value = self[key]
does perform a superfluous dict
lookup in the second line so inside a loop the shorthand may give a performance benefit.
In the general case, it's even a bit more complicated than I spelled out above. The shorthand assignment is actually equivalent to
__some_temporary = type(self)()
value = __some_temporary
self[key] = __some_temporary
and the simplified form value = type(self)(); self[key] = value
ensues only because value
is a simple local variable. If value
were replaced by an expression of the form container[key]
that might fail, the equivalence would no longer hold.