Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python equivalent to Perl's Data::Dumper for inspecting data structures?

Is there a Python module that can be used in the same way as Perl's Data::Dumper module?

Edit: Sorry, I should have been clearer. I was mainly after a module for inspecting data rather than persisting.

BTW Thanks for the answers. This is one awesome site!

like image 391
Rob Wells Avatar asked Mar 29 '10 19:03

Rob Wells


4 Answers

Data::Dumper has two main uses: data persistence and debugging/inspecting objects. As far as I know, there isn't anything that's going to work exactly the same as Data::Dumper.

I use pickle for data persistence.

I use pprint to visually inspect my objects / debug.

like image 195
jjfine Avatar answered Nov 18 '22 07:11

jjfine


I think the closest you will find is the pprint module.

>>> l = [1, 2, 3, 4]
>>> l.append(l)
>>> d = {1: l, 2: 'this is a string'}
>>> print d
{1: [1, 2, 3, 4, [...]], 2: 'this is a string'}

>>> pprint.pprint(d)
{1: [1, 2, 3, 4, <Recursion on list with id=47898714920216>],
 2: 'this is a string'}
like image 31
JimB Avatar answered Nov 18 '22 06:11

JimB


Possibly a couple of alternatives: pickle, marshal, shelve.

like image 6
Juho Vepsäläinen Avatar answered Nov 18 '22 07:11

Juho Vepsäläinen


I too have been using Data::Dumper for quite some time and have gotten used to its way of displaying nicely formatted complex data structures. pprint as mentioned above does a pretty decent job, but I didn't quite like its formatting style. That plus pprint doesn't allow you to inspect objects like Data::Dumper does:

Searched on the net and came across these:

https://gist.github.com/1071857#file_dumper.pyamazon

>>> y = { 1: [1,2,3], 2: [{'a':1},{'b':2}]}

>>> pp = pprint.PrettyPrinter(indent = 4)
>>> pp.pprint(y)
{   1: [1, 2, 3], 2: [{   'a': 1}, {   'b': 2}]}

>>> print(Dumper.dump(y)) # Dumper is the python module in the above link
{
    1: [
        1 
        2 
        3
    ] 
    2: [
        {
            'a': 1
        } 
        {
            'b': 2
        }
    ]
}
>>> print(Dumper.dump(pp))
instance::pprint.PrettyPrinter
    __dict__ :: {
        '_depth': None 
        '_stream': file:: > 
        '_width': 80 
        '_indent_per_level': 4
    }

Also worth checking is http://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py It has its own style and seems useful too.

like image 4
Saurabh Hirani Avatar answered Nov 18 '22 07:11

Saurabh Hirani