file handling if compression has been requestedwe use the gzip module' gzip open(function to open the fileotherwisewe use the built-in open(function we must use "write binarymode ("wb"when pickling data in binary format in python and pickle highest_protocol is protocol compact binary pickle format this is the best protocol to use for data shared among python programs for error handling we have chosen to report errors to the user as soon as they occurand to return boolean to the caller indicating success or failure and we have used finally block to ensure that the file is closed at the endwhether there was an error or not in we will use more compact idiom to ensure that files are closed that avoids the need for finally block context managers this code is very similar to what we saw in the preceding but there is one subtle point to note the pickled data is selfa dict but the dictionary' values are incident objectsthat isobjects of custom class the pickle module is smart enough to be able to save objects of most custom classes without us needing to intervene in generalbooleansnumbersand strings can be pickledas can instances of classes including custom classesproviding their private __dict__ is picklable in additionany built-in collection types (tupleslistssetsdictionariescan be pickledproviding they contain only picklable objects (including collection typesso recursive structures are supportedit is also possible to pickle other kinds of objects or instances of custom classes that can' normally be pickled ( because they have nonpicklable attribute)either by giving some help to the pickle module or by implementing custom pickle and unpickle functions all the relevant details are provided in the pickle module' online documentation __dict__ to read back the pickled data we need to distinguish between compressed and an uncompressed pickle any file that is compressed using gzip compression begins with particular magic number magic number is sequence of one or more bytes at the beginning of file that is used to indicate the file' type for gzip files the magic number is the two bytes bwhich we store in bytes variablegzip_magic "\ \ bfor more about the bytes data typesee the sidebar "the bytes and bytearray data types( )and tables and - )which list their methods here is the code for reading an incidents pickle fileprotocol is python -specific if we want pickles that are readable and writable by both python and python programswe must use protocol instead notethoughthat protocol files written by python can be read by python and python xbut not by python