Pickle in a Python Jar ?!?!

Pickling, serializing, marshaling, or flattening, they are all names that you can intersect with when you learn deep Python. What is the meaning of pickling? This is a question that I want to answer it today.

When I was studying the content in “Head First Python” book by O’reilly, I saw a term pickle. I thought the book was making it interesting and teach it that way. However, it was using the real term.

import pickle  # This is the way that you call the module

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. Pickling/Serializing – is the process whereby a Python object hierarchy is converted into a byte stream, and Unpickling/De-serializing – is the inverse operation, whereby a byte stream is converted back into an object hierarchy.

If we want to save, reuse, or send to someone else our data structure which locates in our memory, we have several ways to make this process happen.

“Many games allow you to save your progress when you quit the game and pick up where you left off when you relaunch the game. (Actually, many non-gaming applications do this as well.) In this case, a data structure that captures “your progress so far” needs to be stored on disk when you quit, then loaded from disk when you relaunch. The data is only meant to be used by the same program that created it, never sent over a network, and never read by anything other than the program that created it. Therefore, the interoperability issues are limited to ensuring that later versions of the program can read data written by earlier versions. ” (Dive-Into-Python3)

Python has a module inside of its standard library called pickle, for situations like above. Let’s see the usage of pickle module:

# This code saves a dictionary into a pickle file.
import pickle
favorite_color = {"lion": "yellow", "kitty": "red"}
pickle.dumb(favorite_color, open("save.p", "wb"))

# This code loads the dictionary back from the pickle file.
import pickle
favorite_color = pickle.load( open("save.p", "rb"))

For further reading I suggest the official pickle documentation

Talk is cheap. Show me the code.

Linus Torvalds

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s