Description of the Python Pickle Class Library (object serialization and deserialization)

Source: Internet
Author: User
Tags object serialization
First, Pickle

The pickle module is used for serializing and deserializing Python objects. Typically, pickle Python objects into binary streams or files.

Serialization and deserialization of Python objects to and from files:

The code is as follows:


Pickle.dump ()
Pickle.load ()


If you want to implement serialization and deserialization between Python objects and strings, use:

The code is as follows:


Pickle.dumps ()
Pickle.loads ()



Types that can be serialized are:
* None,true and False;
* integers, floating-point numbers, complex numbers;
* String, byte stream, array of bytes;
* Contains tuples,lists,sets and dictionaries that can pickle objects;
* Functions defined at the top of module:
* Built-in functions defined at the top of the module;
* Classes defined at the top of the module;
* has a custom type of __dict__ () or __setstate__ ();

Note: The serialization of a function or class is identified by name, so the corresponding module is required for import.

Second, the operation process of pickle

In most cases, if the object picklable, we do not need additional code. By default pickle will intelligently check the properties of classes and instances, and when a class instance is deserialized, its __init__ () method is usually not called. Instead, you first create an uninitialized instance, and then reply to the stored properties.

However, you can modify the default behavior by implementing the following methods:

The code is as follows:


OBJECT.__GETSTATE__ (): The __dict__ of the object is serialized by default, but if you implement __getstate__ (), the value returned by the __getstate__ () function is serialized.
OBJECT.__SETSTATE__ (State): If the type implements this method, this method is used to restore the object's properties when deserializing.
Object.__getnewargs__ (): If the instance constructs (__new__ ()) requires parameters, you need to implement this function.


Note: if __getstate__ () returns false, __setstate__ () is not called when deserializing.

Sometimes the __reduce__ () function needs to be implemented for efficiency, or if the above 3 functions do not meet the requirements.

Third, examples

The code is as follows:


Import Pickle

# an arbitrary collection of objects supported by pickle.
data = {
' A ': [1, 2.0, 3, 4+6j],
' B ': ("character string", B "byte string"),
' C ': Set ([None, True, False])
}

With open (' Data.pickle ', ' WB ') as F:
# Pickle the ' data ' dictionary using the highest protocol available.
Pickle.dump (data, F, pickle. Highest_protocol)


With open (' Data.pickle ', ' RB ') as F:
# The protocol version used is detected automatically
# has to specify it.
data = Pickle.load (f)
Print (str (data))

Iv. Modifying the default behavior of the picklable type

The code is as follows:


Class TextReader:
"" "Print and number lines in a text file." "

def __init__ (self, filename):
Self.filename = filename
Self.file = open (filename)
Self.lineno = 0

def readline (self):
Self.lineno + = 1
line = Self.file.readline ()
If not line:
Return None
If Line.endswith (' \ n '):
line = Line[:-1]
Return "%i:%s"% (Self.lineno, line)

def __getstate__ (self):
# Copy The object ' s state from self.__dict__ which contains
# all our instance attributes. Always use the dict.copy ()
# method to avoid modifying the original state.
State = Self.__dict__.copy ()
# Remove the unpicklable entries.
Del state[' file ']
return state

def __setstate__ (self, State):
# Restore instance attributes (i.e., filename and Lineno).
Self.__dict__.update (state)
# Restore the previously opened file ' s state. To doing so, we need to
# reopen it and read from it until the line count is restored.
File = open (Self.filename)
For _ in range (Self.lineno):
File.readline ()
# Finally, save the file.
Self.file = File

Reader = TextReader ("Hello.txt")
Print (Reader.readline ())
Print (Reader.readline ())
s = pickle.dumps (reader)
#print (s)
New_reader = Pickle.loads (s)
Print (New_reader.readline ())

# The output is
# 1:hello
# 2:how is You
# 3:goodbye

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.