[IPython-dev] _repr_pretty_() for dict subclasses

Walter Dörwald walter at livinglogic.de
Fri Mar 23 13:07:53 EDT 2012


Hello all!

I'm currently experimenting with the new pretty printing framework. It 
seems there's a problem with the _repr_pretty_ method in dict subclasses:

    Python 3.2.2 (default, Oct 31 2011, 16:56:14)
    Type "copyright", "credits" or "license" for more information.

    IPython 0.12 -- An enhanced Interactive Python.
    ?         -> Introduction and overview of IPython's features.
    %quickref -> Quick reference.
    help      -> Python's own help system.
    object?   -> Details about 'object', use 'object??' for extra details.
    In [1]: class Element(object):
       ...:     def _repr_pretty_(self, p, cycle):
       ...:         p.text("Element()")
       ...:
    In [2]: class Attrs(dict):
       ...:     def _repr_pretty_(self, p, cycle):
       ...:         p.text("Attrs()")
       ...:
    In [3]: Element()
    Out[3]: Element()
    In [4]: Attrs()
    Out[4]: {}
    In [5]:

I would have expected the second output to be:

    Out[4]: Attrs()

The problem is in

    IPython.lib.pretty.RepresentationPrinter.pretty()

The code first tries to find a registered printers for any of the base 
classes in type_pprinters. This ignores any _repr_pretty_ method defined 
earlier in the mro. The current order is:

    # First try to find registered singleton printers for the type.
    # Next look for type_printers.
    # Finally look for special method names.

Changing this to:

    # First try to find registered singleton printers for the type.
    # Next look for special method names.
    # Finally look for type_printers.

would solve this particular problem, however this leads to the inverse 
problem: Looking up the method (which might be implemented in a base 
class) first would ignore any registered printers for the class itself.

The proper solution would probably be to walk the mro and see if there's 
either a registered printer or a _repr_pretty_ method for the class. 
However I'm not sure if there's a reliable way to check whether a method 
is implemented in the class itself or inherited from any of the base 
classes.

What's the proper fix for this? Should I submit a bug report? Work on a 
patch?

Servus,
    Walter



More information about the IPython-dev mailing list