Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print an object in Python [duplicate]

Tags:

python

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': {...}}}
like image 868
Weil Avatar asked Oct 22 '25 13:10

Weil


1 Answers

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.

like image 102
Trey Hunner Avatar answered Oct 25 '25 04:10

Trey Hunner