[TIP] dicts in doctests

Pete pfein at pobox.com
Wed Sep 17 17:43:43 PDT 2008


Hiya-

Is there a preferred way of testing dicts in doctests?  The random key  
ordering can be problematic (IIRC, this bit the django port to Jython).

 >>> dict([('x', 1), ('y', 2)])
{'x': 1, 'y': 2}

Python doesn't guarantee what order the dict is printed in.  It'd be  
possible to work around like so:

 >>> dict([('x', 1), ('y', 2)]) == {'x': 1, 'y': 2}
True

or even

 >>> d = dict([('x', 1), ('y', 2)])
 >>> sorted(d.items())
[('x': 1), ('y': 2)]

But both of these approaches kinda defeat the tests as documentation  
benefit.

Any thoughts?  Just go with the first case & hope for the best?  The  
ordering's relatively stable across CPythons (versions & platforms)  
AFAIK...

--Pete




More information about the testing-in-python mailing list