Method Name:
dumps
Method Signature:
dumps(object, pickleProtocol=None, *, fix_imports=True)
Parameters:
object – The python object that is to be pickled(serialized)
pickleProtocol – One of the Python pickling protocol versions as defined by the pickle module
fix_imports – When True the pickling format is compatible with Python 2.0
Return Value:
Returns the bytes object for the pickled Python object.
Method Overview:
- The dumps() method of the Python pickle module serializes a python object hierarchy and returns the bytes object of the serialized object.
- The difference between the dump() method and the dumps() method is, the dumps() does not deal with writing the pickled object hierarchy into the disk file.
- Whereas, the dump() method can write the pickled python object into a file object or into a BytesIO object or to any other destination object that has an interface with a write() method accepting a bytes argument.
Example:
import pickle
class Film: title = "" direction = "" music = "" caste = "" year = -1 video = None
def __init__(self, title, direction, music, cast, video): self.title = title self.direction = direction self.music = music self.cast = cast self.video = None
def identify(self): print("Movie title:%s"%(self.title)) print("Directed by:%s"%(self.direction)) print("Music:%s"%(self.music)) print("Cast:%s"%(self.cast)) print("Video Buffer:%s"%(self.video))
# Create a film instance film = Film("Sound Of Music", "Robert Wise", ["Julie Andrews", "Christopher Plummer"], 1965, None)
# Print the film info film.identify()
# Pickle the python object pickledObject = pickle.dumps(film)
# pickledObject can be written to a file, to a binary stream and so on print(pickledObject) |
Output:
Movie title:Sound Of Music Directed by:Robert Wise Music:['Julie Andrews', 'Christopher Plummer'] Cast:1965 Video Buffer:None b'\x80\x03c__main__\nFilm\nq\x00)\x81q\x01}q\x02(X\x05\x00\x00\x00titleq\x03X\x0e\x00\x00\x00Sound Of Musicq\x04X\t\x00\x00\x00directionq\x05X\x0b\x00\x00\x00Robert Wiseq\x06X\x05\x00\x00\x00musicq\x07]q\x08(X\r\x00\x00\x00Julie Andrewsq\tX\x13\x00\x00\x00Christopher Plummerq\neX\x04\x00\x00\x00castq\x0bM\xad\x07X\x05\x00\x00\x00videoq\x0cNub.' |