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 afte
Possibly a couple of alternatives: pickle, marshal, shelve.
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'}
Isn't it true that all the answers ignore dumping anything else than a combination of the basic data types like lists, dicts, etc.? I have just ran pprint on an Python Xlib Window object and got… <<class 'Xlib.display.Window'> 0x004001fe>
… that's all. No data fields, no methods listed… Is there anything that does a real dump of an object? With e.g.: all its attributes?
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.
If you want something that works better than pprint, but doesn't require rolling your own, try importing dumper from pypi:
https://github.com/jric/Dumper.py or
https://github.com/ericholscher/pypi/blob/master/dumper.py
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.
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.