At some point, any Python programmer will need to pack some object and hide it until better times. Say in the config file. Or pass through a socket. How to do it? Of course, you can write a small class that will generate and parse the XML code (by the way, the next article will be about this), but this is too much of a hassle.
Not! Our pick is Pickle!
Preamble
Pickle (English canned, pickled) - module serialization and deserialization of objects in Python for subsequent transfer.
What types of data does Pickle pack?
- None, True, False
- Strings (regular or unicode)
- Standard Numeric Data Types
- Dictionaries, lists, tuples
- Functions
- Classes
But there is one small detail. At first, you will be quite pleased with the work of this module, but later, when you use it on high-load projects, you will begin to notice that data canning takes more time than we would like. This problem was solved by the fact that a similar module was written, but not on Python, but on C, which accelerated its performance thousands of times (according to the developers). Yes, sometimes modules written in C work faster than their Python counterparts, but there are subtleties in which I allow myself not to go into this article.
')
The creators of Python themselves in the official documentation suggest 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 about 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.
Canning an object into a string:
import cPickle as pickle
obj = {"one": 123, "two": [1, 2, 3]}
output = pickle.dumps(obj, 2)
As you can see, nothing complicated, the object is ready to be sent.
Now you need to unpack it back. This is even easier:
obj = pickle.loads(output)
The canning protocol is determined automatically.
Let's try to pack the object into a file.
import cPickle as pickle
obj = {"one": 123, "two": [1, 2, 3]}
output = open('data.pkl', 'wb')
pickle.dump(obj, output, 2)
output.close()
Please note that the write mode to the file must necessarily be wb, that is, the file is overwritten in binary mode. For reading mode should be rb:
import cPickle as pickle
input = open('data.pkl', 'rb')
obj = pickle.load(input)
input.close()
Thanks for attention. Next time I would like to talk about the features of creating and parsing XML data in Python.