Search code examples
pythonpickledata-persistence

python pickle: what is it? when would i use it?


I get the idea that pickle is an object persistence library that lets me write out a data structure to disk, and reload it.

Why/when would I do this vs the 'traditional' method of using a text file?

EDIT: Actually that isn't a helpful way to phrase the question. I mean what are the situations where pickle would be easier/more convenient, and when would it get me into trouble? What sort of data or design pattern lends itself to pickle?


Solution

  • When you want to store Python objects that aren't text, aren't easily serialized with other libraries (JSON, msgpack, etc), and don't want to write your own serialization and deserialization code.

    Generally speaking, pickle should be a serialization and deserialization method of last resort: It isn't speedy (msgpack is far faster and more compact), isn't secure (don't ever use pickle as a storage format for cookies or other client-accessible data!), isn't interoperable (no implementations for non-Python languages exist)... but it works for objects and data types which aren't generally supported elsewhere (though not all Python objects).