Is there anything in python that lets me dump out a random object in such a way as to see its underlying data representation?
I am coming from Perl where Data::Dumper does a reasonable job of letting me see how a data structure is laid out. Is there anything that does the same thing in python?
Thanks!
Well
Dumperin Perl gives you a representation of an object that can beeval‘d by the interpreter to give you the original object. An object’sreprin Python tries to do that, and sometimes it’s possible. Adict‘srepror astr‘sreprdo this, and some classes likedatetimeandtimedeltaalso do this. Sorepris as much the equivalent ofDumperbut it’s not pretty and doesn’t show you the internals of an object. For that you can usedirand roll your own printer.Here’s my shot at a printer that would not result in
eval-able Python code and thus should be used to generate a string of the object instead:In the above example, I’ve overridden the object’s default
__str__implementation.__str__is what gets called when you try to represent the object as a string, or format it using a string formatting function.BTW
repris what gets printed when you doprint obj, it invokes the__repr__method on that object. See the Python documentation of__repr__for more information on how to control the formatting of objects.The output from the above code was