views:

248

answers:

4

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!

+4  A: 

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

bebraw
`marshal` is almost certainly not what anyone wants.
Mike Graham
+7  A: 

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.

jjfine
Plus, a simple "print" in Python partly does what Data::Dumper does for Perl.
EOL
+1  A: 

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'}
JimB
+2  A: 
  • For serialization, there are many options.

    • One of the best is JSON, which is a language-agnostic standard for serialization. It is available in 2.6 in the stdlib json module and before that with the same API in the third-party simplejson module.

    • You do not want to use marshal, which is fairly low-level. If you wanted what it provides, you would use pickle.

    • I avoid using pickle the format is Python-only and insecure. Deserializing using pickle can execute arbitrary code.

      • If you did use pickle, you want to use the C implementation thereof. (Do import cPickle as pickle.)
  • For debugging, you usually want to look at the object's repr or to use the pprint module.

Mike Graham