These semantics are intended to match those of update as closely
as possible. For the dict built-in itself, calling keys is
redundant as iteration over a dict iterates over its keys; but for
subclasses or other mappings, update prefers to use the keys
method.
The above paragraph may be inaccurate.
Although the dict docstring states that keys
will be called if it exists, this does not seem to
be the case for dict subclasses. Bug or feature?
>>> print(dict.update.__doc__)
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
It's
actually pretty interesting... and misleading/wrongish. It never says that keys is
*called*... in reality, it just checks for the "keys" method before deciding whether to
proceed with PyDict_Merge or PyDict_MergeFromSeq2. It should really read more like:
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present, has a .keys() method, and is a subclass of dict, then does: for k in E: D[k] = E[k]
If E is present, has a .keys() method, and is not a subclass of dict, then does: for k in E.keys(): D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
Should our __sub__ behavior be the same (i.e., iterate for dict subclasses and objects without "keys()", otherwise call "keys()" and iterate over that)? __iadd__ calls into this logic already. It seems to be the most "natural" solution here, if we desire behavior analogous to "update".
Brandt