tags:

views:

116

answers:

3

I've looked at the pickle documentation, but I don't understand where pickle is useful.

What are some common use-cases for pickle?

+4  A: 

Minimal roundtrip example..

>>> import pickle
>>> a = Anon()
>>> a.foo = 'bar'
>>> pickled = pickle.dumps(a)
>>> unpickled = pickle.loads(pickled)
>>> unpickled.foo
'bar'

Edit: but as for the question of real-world examples of pickling, perhaps the most advanced use of pickling (you'd have to dig quite deep into the source) is ZODB: http://svn.zope.org/

Otherwise, PyPI mentions several: http://pypi.python.org/pypi?:action=search&term=pickle&submit=search

I have personally seen several examples of pickled objects being sent over the network as an easy to use network transfer protocol.

Jacob Oscarson
+4  A: 

I have used it in one of my projects. If the app was terminated during it's working (it did a lengthy task and processed lots of data), I needed to save the whole data structure and reload it after the app was run again. I used cPickle for this, as speed was a crucial thing and the size of data was really big.

taskinoor
+6  A: 

Some uses that I have come across:

1) saving a program's state data to disk so that it can carry on where it left off when restarted (persistence)

2) sending python data over a TCP connection in a multi-core or distributed system (marshalling)

3) storing python objects in a database

4) converting an arbitrary python object to a string so that it can be used as a dictionary key (e.g. for caching & memoization).

There are some issues with the last one - two identical objects can be pickled and result in different strings - or even the same object pickled twice can have different representations. This is because the pickle can include reference count information.

Dave Kirby
One should not transfer pickled objects over network or other untrusted channels, unless the pickled data is carefully secured against manipulation. The pickle documentation explicitly warns to *never* unpickle data from untrusted or unauthenticated sources.
lunaryorn
@lunaryorn: good point. If you are going to transfer pickled data between machines then use a secure channel such as SSL or SSH tunnelling.
Dave Kirby
@Dave: Then you are still trusting the endpoint not to exploit you, which may or not be okay, depending on context.
Longpoke