[issue10017] pprint.pprint raises TypeError on dictionaries with user-defined types as keys

Arnaud Delobelle report at bugs.python.org
Sat Oct 2 22:35:20 CEST 2010


New submission from Arnaud Delobelle <arnodel at googlemail.com>:

The pprint function in the python 3.1 pprint module fails when
printing a dictionary containing more than one item and with one item
being a user-defined type.  It seems pprint tries to sort the keys but
fails, (maybe because calling __lt__ on a user-defined type doesn't
bind its first argument to 'self'?  Looking into pprint.py would
probably yield the answer).

This seems related to issue 3976 but it was fixed in r76389 and
r76390.  My example below fails in r79147.  I'm not in a position to check more recent revisions right now.

In Python 2.6, the following works fine:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pprint import pprint
>>> class A(object): pass
... 
>>> pprint({A:1, 1:2})
{1: 2, <class __main__.A at 0xb77dc47c>: 1}


But in Python 3.1, it fails with the error below:

Python 3.1.2 (r312:79147, Apr 15 2010, 12:35:07) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pprint import pprint
>>> class A: pass
... 
>>> pprint({A:1, 1:2})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.1/pprint.py", line 55, in pprint
    printer.pprint(object)
  File "/usr/lib/python3.1/pprint.py", line 132, in pprint
    self._format(object, self._stream, 0, 0, {}, 0)
  File "/usr/lib/python3.1/pprint.py", line 155, in _format
    rep = self._repr(object, context, level - 1)
  File "/usr/lib/python3.1/pprint.py", line 242, in _repr
    self._depth, level)
  File "/usr/lib/python3.1/pprint.py", line 254, in format
    return _safe_repr(object, context, maxlevels, level)
  File "/usr/lib/python3.1/pprint.py", line 296, in _safe_repr
    items = sorted(object.items(), key=_safe_tuple)
  File "/usr/lib/python3.1/pprint.py", line 89, in __lt__
    rv = self.obj.__lt__(other.obj)
TypeError: expected 1 arguments, got 0

----------
components: Library (Lib)
messages: 117895
nosy: arno
priority: normal
severity: normal
status: open
title: pprint.pprint raises TypeError on dictionaries with user-defined types as keys
versions: Python 3.1

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


More information about the Python-bugs-list mailing list