Search code examples
pythonpython-3.6pretty-print

PrettyPrint with Mutable Mapping


I had a nested dict in my project, which was printed via PrettyPrint (just throw the nested dict into it).

But this nested dict had to be replaced by nested MutableMapping Objects, because I needed to overwrite some MagicMethods. But because it's an object now, it is just taking the first key and prints out, that the value is a my_dict object.

How can I PrettyPrint now such a MutableMapping Object with a dict attribute?

class my_dict(collections.abc.MutableMapping):
    def __init__(self):
        print("dict was created")
        self.d = dict() # var where I want to store my key/values

    def __setitem__(self, key, value):
        # do sth else
        print("Dict Element was set: Key:\t{}, Value:\t{}".format(key, value))
        self.d[key] = value
        return

    def __getitem__(self, key):
        # do sth else
        print("Item was requested")
        return self.d[key]

    def __delitem__(self, key):
        del self.d[key]

    def __iter__(self):
        return self.d.__iter__()

    def __len__(self):
        return len(self.d)

    def sd(self, k, d):
        if k not in self:
            self[k] = d
        return self[k]

I'm using Python 3.6.


Solution

  • pprint just formats the string returned by __repr__, and prints it. Add the following dunder method to your class.

    def __repr__(self):
        return self.d.__repr__()
    

    Edited

    from pprint import PrettyPrinter
    PrettyPrinter._dispatch[my_dict.__repr__] = PrettyPrinter._pprint_dict
    

    pprint will print as though it was called with the inner dict self.d. PrettyPrinter has an internal dict called _dispatch which maps class.__repr__ => pprint_method. So you have to add a pprint method for your class. In this case, I mapped my_dict.__repr__ to the pprint method for dict, so pprint formats my_dict objects as if they were dicts.

    pprint source code is in plain python here.