Object conservation in Python
At some point, any Python programmer will need to pack some object and hide it until better times. Say in a config file. Or pass through a socket. How to do it? Of course, you can write a small class that will generate and parse XML code (by the way, the next article will be about that), but this is too much trouble.
Not! Our choice is Pickle!
Pickle (Eng. Preserve, Pickle) - a module for serializing and deserializing objects in Python for their subsequent transfer.
What types of data can Pickle pack?
The creators of Python themselves in the official documentation advise using cPickle, and in order not to modify the program for a long time, you can connect cPickle like this:
How to use conservation of objects? You have two options: either preserve the object in a string (which can be passed through a socket, for example) or directly to a file.
There are three conservation protocols:
Not! Our choice is Pickle!
Preamble
Pickle (Eng. Preserve, Pickle) - a module for serializing and deserializing objects in Python for their subsequent transfer.
What types of data can Pickle pack?
- None, True, False
- Strings (regular or Unicode)
- Standard numeric data types
- Dictionaries, lists, tuples
- Functions
- Classes
The creators of Python themselves in the official documentation advise using cPickle, and in order not to modify the program for a long time, you can connect cPickle like this:
import cPickle as pickle
The basics
How to use conservation of objects? You have two options: either preserve the object in a string (which can be passed through a socket, for example) or directly to a file.
There are three conservation protocols:
- Version 0 , standard ASCII protocol. It should be used only for compatibility with earlier versions of Python.
- Version 1 is roughly the same, used for compatibility with older versions of Python.
- Version 2 was first introduced in version 2.3, it best packs objects written in modern syntax, I recommend using it.
import cPickle as pickle
obj = {"one": 123, "two": [1, 2, 3]}
output = pickle.dumps(obj, 2)
obj = pickle.loads(output)
import cPickle as pickle
obj = {"one": 123, "two": [1, 2, 3]}
output = open('data.pkl', 'wb')
pickle.dump(obj, output, 2)
output.close()
import cPickle as pickle
input = open('data.pkl', 'rb')
obj = pickle.load(input)
input.close()