The insertion-order of keyword arguments is now guaranteed to be preserved in the 3.6 version of Python. This has been made possible by a change to the underlying representation of the dict
object.
However, it has been stated - somewhat strenuously - that the order preservation of the dict
object should not be relied upon in general as of yet. The docs explain the situation this way:
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).
PEP 468 does not mention anything about copying the keyword arguments. But there are times when one may wish to iterate over a copy of the kwargs
arguments (e.g. while mutating kwargs
in a for loop):
def i_will_never_fail(**kwargs):
for thing1,thing2 in zip(kwargs.copy(), kwargs):
assert thing1==thing2
My question is: should the order of the object resulting from kwargs.copy()
be considered guaranteed as well? Or should this also be considered an implementation detail? Is the OrderedDict
only mostly dead?