[New-bugs-announce] [issue7429] PrettyPrinter cannot print dicts with unsortable keys

Martin Altmayer report at bugs.python.org
Thu Dec 3 19:30:48 CET 2009


New submission from Martin Altmayer <martin.altmayer at web.de>:

In the following code I use a class for dictionary-keys that has a
__hash__-function but cannot be ordered and try to print that dictionary
with a PrettyPrinter.

import pprint
pp = pprint.PrettyPrinter()

# A class that supports hashing and comparison for equality but cannot
be ordered
class KeyClass:
    def __init__(self,id):
        self.id = id
        
    def __eq__(self,other):
        return self.id == other.id
        
    def __ne__(self,other):
        return self.id != other.id
        
    def __hash__(self):
        return self.id
    

dictionary = dict.fromkeys([KeyClass(i) for i in range(10)])
pp.pprint(dictionary)

The script crashes with the following errors:

Traceback (most recent call last):
  File "/usr/local/lib/python3.1/pprint.py", line 272, in _safe_repr
    items = sorted(items)
TypeError: unorderable types: KeyClass() < KeyClass()

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "bug.py", line 20, in <module>
    pp.pprint(dictionary)
  File "/usr/local/lib/python3.1/pprint.py", line 106, in pprint
    self._format(object, self._stream, 0, 0, {}, 0)
  File "/usr/local/lib/python3.1/pprint.py", line 129, in _format
    rep = self._repr(object, context, level - 1)
  File "/usr/local/lib/python3.1/pprint.py", line 216, in _repr
    self._depth, level)
  File "/usr/local/lib/python3.1/pprint.py", line 228, in format
    return _safe_repr(object, context, maxlevels, level)
  File "/usr/local/lib/python3.1/pprint.py", line 277, in _safe_repr
    items = sorted(items, key=sortkey)
TypeError: unorderable types: KeyClass() < KeyClass()

----------
components: None
messages: 95939
nosy: maranos
severity: normal
status: open
title: PrettyPrinter cannot print dicts with unsortable keys
versions: Python 3.1

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue7429>
_______________________________________


More information about the New-bugs-announce mailing list