Python Forum

Full Version: dumping an object
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i'm often dealing with an object that apparently is in a different state than expected. i run into this a few times and have to add and change a lot of code to figure it out. i'd like to just dump everything out so i can see the object when debugging. when i use repr() on it i often just get something like '<foo object at 0x0123456789ab>'. is there anything better than repr() for this?
i have already written a big function called print_object(). i think i just need to add more things to it, like support for attributes. it was an early project. it probably has a lot of bad code. i should, also, clean it up.

the purpose of print_object was to produce output that is easy to read and is valid Python code that can recreate the object. i would probably have to abandon recreatability to support attributes, since a literal cannot usually set these. it is recursive and explodes each referenced object. every leaf item is printed on a separate line. strings are showed with a slice at the end that yields the whole string with its actual length as a way to quickly see how long the string is. dictionaries are shown with keys sorted for human convenience. i think sets are sorted, too. it was originally written for Python 2 and has been tweaked to get it working on Python 3.