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()
|