We are searching data for your request:
Upon completion, a link will appear to access the found materials.
Pickle, which is part of the Python library by default, is an important module whenever you need persistence between user sessions. As a module, pickle provides for the saving of Python objects between processes.
Whether you are programming for a database, game, forum, or some other application that must save information between sessions, pickle is useful for saving identifiers and settings. The pickle module can store things such as data types such as booleans, strings, and byte arrays, lists, dictionaries, functions, and more.
Note: The concept of pickling is also known as serialization, marshaling, and flattening. However, the point is always the same-to save an object to a file for later retrieval. Pickling accomplishes this by writing the object as one long stream of bytes.
Pickle Example Code in Python
To write an object to a file, you use a code in the following syntax:
object = Object()
filehandler = open(filename, 'w')
Here's how a real-world example looks:
object_pi = math.pi
file_pi = open('filename_pi.obj', 'w')
This snippet writes the contents of object_pi to the file handler file_pi, which in turn is bound to the file filename_pi.obj in the directory of execution.
To restore the value of the object to memory, load the object from the file. Assuming that pickle has not yet been imported for use, start by importing it:
filehandler = open(filename, 'r')
object = pickle.load(filehandler)
The following code restores the value of pi:
file_pi2 = open('filename_pi.obj', 'r')
object_pi2 = pickle.load(file_pi2)
The object is then ready for use once again, this time as object_pi2. You can, of course, reuse the original names, if you prefer. This example uses distinct names for clarity.
Things to Remember About Pickle
Keep these things in mind when using the pickle module:
- The pickle protocol is specific to Python - it's not guaranteed to be cross-language compatible. You most likely cannot transfer the information to make it useful in Perl, PHP, Java, or other languages.
- There is also no guarantee of compatibility between different versions of Python. IThe incompatibility exists because not every Python data structure can be serialized by the module.
- By default, the latest version of the pickle protocol is used. It remains that way unless you manually change it.
Tip: Also find out how to use shelve to save objects in Python for another method of maintaining object continuity.