4

I have a dictionary like:

{'string': u'abc', 'object': <DEMO.Detail object at 0xb5b691ac>}

How can I make it show the contents of the DEMO.Detail object's __dict__, like so?

{'string': u'abc', 'object': {'obj_string': u'xyz', 'obj_object': {...}}}
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Weil
  • 71
  • 1
  • 1
  • 4

2 Answers2

6

If you are the creator of DEMO.Detail, you could add __repr__ and __str__ methods:

class Detail:
    def __str__(self):
        return "string shown to users (on str and print)"
    def __repr__(self):
        return "string shown to developers (at REPL)"

This will cause your object to function this way:

>>> d = Detail()
>>> d
string shown to developers (at REPL)
>>> print(d)
string shown to users (on str and print)

In your case I assume you'll want to call dict(self) inside __str__.

If you do not control the object, you could setup a recursive printing function that checks whether the object is of a known container type (list, tuple, dict, set) and recursively calls iterates through these types, printing all of your custom types as appropriate.

There should be a way to override pprint with a custom PrettyPrinter. I've never done this though.

Lastly, you could also make a custom JSONEncoder that understands your custom types. This wouldn't be a good solution unless you actually need a JSON format.

Trey Hunner
  • 10,975
  • 4
  • 55
  • 114
  • I think I will setup a recursive printing function to print this object. Thank you. – Weil Nov 17 '15 at 02:35
1

Could prettyprint do it?

>>> import pprint
>>> a = {'foo':{'bar':'yeah'}}
>>> pprint.pprint(a)
{'foo': {'bar': 'yeah'}}

If your objects have __repr__ implemented, it can also print those.

import pprint
class Cheetah:
    def __repr__(self):
        return "chirp"

zoo = {'cage':{'animal':Cheetah()}}
pprint.pprint(zoo) 

# Output: {'cage': {'animal': chirp}}
martineau
  • 119,623
  • 25
  • 170
  • 301
Bemmu
  • 17,849
  • 16
  • 76
  • 93
  • I don't have super high confidence in my answer, there is probably a better solution out there. – Bemmu Nov 16 '15 at 07:40
  • 2
    I am just trying to understand the code. Not to bash your answer. It just gives the same output with `print`. May be a better example would show the difference – akrun Nov 16 '15 at 07:41
  • 1
    @akrun Yeah, I was expecting it to format it better, but looks just the same as print. – Bemmu Nov 16 '15 at 07:42
  • @Bemmu thank for your help, but i can't change the object inside "myobject". I want to print it out same as "myobject" without edit it. – Weil Nov 16 '15 at 08:40