[IPython-dev] _repr_pretty_() for dict subclasses
Robert Kern
robert.kern at gmail.com
Fri Mar 23 13:24:18 EDT 2012
On 3/23/12 5:07 PM, Walter Dörwald wrote:
> 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.
It will be in the __dict__ of the class that defines it. The algorithm should
probably be:
1. Try to find registered singleton printers for the type.
2. Walk up the MRO:
a. Look in type_printers for the current class.
b. Then look for _repr_pretty_ in the current class's __dict__.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the IPython-dev
mailing list