Testing dictionary results with doctest

Duncan Booth duncan.booth at invalid.invalid
Fri Oct 31 11:27:26 EDT 2008


Joe Strout <joe at strout.net> wrote:

> What's the standard solution for this?  Should I iterate over the  
> sorted keys and print those out instead?  Is there some built-in  
> method somewhere that will print a dictionary in a reliable order?   
> Does doctest have some special way to tell it to consider the result  
> as a dictionary rather than a string?  Or something else?

pprint will sort a dictionary's keys as well as laying it out with line 
breaks where appropriate.

>>> from pprint import pprint
>>> pprint(t.match( "The rain in Spain falls mainly on the train." ))
{'location': 'Spain', 'object': 'rain', 'subloc': 'train'}

which leaves the question of what you do for this one:

>>> pprint({1j: 'hello', 0: 'world'})

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    pprint({1j: 'hello', 0: 'world'})
  File "C:\Python25\lib\pprint.py", line 55, in pprint
    printer.pprint(object)
  File "C:\Python25\lib\pprint.py", line 106, in pprint
    self._format(object, self._stream, 0, 0, {}, 0)
  File "C:\Python25\lib\pprint.py", line 129, in _format
    rep = self._repr(object, context, level - 1)
  File "C:\Python25\lib\pprint.py", line 195, in _repr
    self._depth, level)
  File "C:\Python25\lib\pprint.py", line 207, in format
    return _safe_repr(object, context, maxlevels, level)
  File "C:\Python25\lib\pprint.py", line 249, in _safe_repr
    for k, v in sorted(object.items()):
TypeError: no ordering relation is defined for complex numbers
>>> 

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list