Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent to Data::Dumper - dumping raw datastructures for inspection?

Just getting into Python and I'm shocked to find that there doesn't seem to be an obvious way to inspect datastructures properly, the way you can using Perl's Data::Dumper module.

For example, pprint will display an object's __repr__ return value, rather than telling me that the value is an object and what kind of object it is.

Data::Dumper will tell you exactly what a datastructure contains, not silently convert Objects into strings, which is absolutely useless for data inspection purposes.

Is there any way to print a raw dump of a datastructure in Python? I suppose I could create something myself, essentially all it needs to do is walk a datastructure and print(type(v), v) but there must be something that does this well?

Edit: it's __repr__ that pprint resolves, not __str__ as I initially said, at least..usually?

So, I think all I really need is pprint that ignores __repr__ definitions. Does that exist?

like image 243
Pete D Avatar asked Sep 17 '25 02:09

Pete D


1 Answers

pprint

from pprint import pprint
pprint(someVar)

OK. I don't have any better answer. I always use 'pprint' or 'pformat'. You can infer the type from the strings output. I think honing that skill of knowing the type from the output is the way to go.

Or as you said, your own print(type(v), v).

With python, the philosophy seems to be something like: "Don't depend on the type too much. Just get an object and use it let the runtime (tests) tell the user if they mucked up": http://en.wikipedia.org/wiki/Duck_typing#In_Python


After reading the comments.

Why not monkey patch the class you want to see to print something useful:

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return "Muahaha"

def main():
    s = Person("Santa", 1500)
    from pprint import pprint
    pprint(s)

    print
    print ".. Go MONKEYS ..."
    print

    # Monkey patch the Person class so it prints nice info from now on
    Person.__repr__ = lambda p: "<%s name='%s' age=%s>" % (p.__class__.__name__, p.name, p.age)
    pprint(s)

if __name__ == '__main__':
    main()

-- output --

matthew@speedy:~/tmp$ python monkey.py
Muahaha

.. Go MONKEYS ...

<Person name='Santa' age=1500>
like image 101
matiu Avatar answered Sep 18 '25 17:09

matiu