Ordered dict by default
Duncan Booth
duncan.booth at invalid.invalid
Thu Feb 5 07:19:09 EST 2009
Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
> Duncan Booth <duncan.booth at invalid.invalid> writes:
>> If you want to write doctests then any stable order in the default
>> dict type would be helpful no matter whether it means that keys are
>> in original insertion or latest insertion order or sorted.
>
> Just use "sorted" in the test code:
> >>> print sorted(dict((a**2,a) for a in xrange(5)).keys())
> [0, 1, 4, 9, 16]
>
No, that only works if you have control over the dict iteration. There are
plenty of situations when tests become unstable because dicts are unstable
and you don't have control over the order of iteration. Also, if you are
using doctests as a form of documentation then you just want to be able to
show the value, or at most pprint it, you don't want to obscure the
documentation with calls to sort.
For example if you have something that creates xml then almost certainly
the library you are using stores the attributes for a tag in a dictionary
and just outputs them in whatever order they iterate over. That's fine for
creating XML but when you want a test like:
>>> mydata.asXml()
<... some xml here except we don't know what order the attributes will
appear in ...>
then you are stuffed. Actually it's also a problem if you want to store the
output XML in Subversion. As with my round-trip coding problem you could
obviously solve it by changing the code to sort the output, but stabilising
the order of dict iteration would solve the problem for all such cases.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list