pickle.dump(pythonObject, pickleDestination, pickle_protocol=None, *, fix_imports=True)
pythonObject – The Python Object to be pickled
pickleDestination – File or buffer to which the pickled object will be written
pickle_protocol – One of the constants as defined by the pickle module specifying the pickle protocol version; When None is specified it refers to the default protocol used for the Python version.
fix_imports – When specified, in accordance with the value for the parameter pickle_protocol, the method dump() will decide whether the pickling process should be compatible with Python version 2 or not. The default value is True. This default parameter should be used as a name value pair only.
Returns the reconstructed Python object from the pickle source. The pickle source could be a file or a memory buffer.
- The dump() method of the pickle module in Python, converts a Python object hierarchy into a byte stream. This process is also called as serilaization.
- The converted byte stream can be written to a buffer or to a disk file.
- The byte stream of a pickled Python object can converted back to a Python object using the pickle.load() method.
title = ""
isbn = ""
parts = None
chapters = None
def __init__(self, title, isbn, parts, chapters):
self.title = title
self.isbn = isbn
self.parts = parts
self.chapters = chapters
print("Title of the book: %s"%(self.title))
print("ISBN of the book: %s"%(self.isbn))
for part in self.parts:
partName = ""
beginChapter = -1
endChapter = -1
def __init__(self, partName, beginChapter, endChapter):
self.partName = partName
self.beginChapter = beginChapter
self.endChapter = endChapter
stringRep = "%s"%(self.partName)
part1 = Part("Part 1", 1, 3)
part2 = Part("Part 2", 4, 5)
part3 = Part("Part 3", 6, 7)
bookTitle = "Book yet to be written";
bookISBN = "XXX-X-XX-XXXXXX-X";
bookParts = [part1, part2, part3]
bookChapters = ["Chapter 1", "Chapter 2", "Chapter 3",
"Chapter 4", "Chapter 5", "Chapter 6",
book = Book(bookTitle, bookISBN, bookParts, bookChapters)
pickleBuffer = io.BytesIO()
print("Pickling of the object into the memory buffer started")
print("Pickling of the object into the memory buffer ended")
print("Pickled buffer beginning address:")
print("Unpickling of the object from memory started")
unpickledBook = pickle.loads(pickleBuffer.getbuffer())
print("Unpickling of the object from memory ended")
print("Printing the attributes of unpickled object")
Pickling of the object into the memory buffer started
Pickling of the object into the memory buffer ended
Pickled buffer beginning address:
<memory at 0x107d09e88>
Unpickling of the object from memory started
Unpickling of the object from memory ended
Printing the attributes of unpickled object
Title of the book: Book yet to be written
ISBN of the book: XXX-X-XX-XXXXXX-X
Chapters are:['Chapter 1', 'Chapter 2', 'Chapter 3', 'Chapter 4', 'Chapter 5', 'Chapter 6', 'Chapter 7']