@@ -560,10 +560,8 @@ referenced object.
560560Here is a comprehensive example presenting how persistent ID can be used to
561561pickle external objects by reference.
562562
563- .. XXX Work around for some bug in sphinx/pygments.
564- .. highlightlang :: python
565563.. literalinclude :: ../includes/dbpickle.py
566- .. highlightlang :: python3
564+
567565
568566.. _pickle-state :
569567
@@ -715,46 +713,35 @@ solutions.
715713
716714.. _pickle-example :
717715
718- Example
719- -------
716+ Usage Examples
717+ --------------
720718
721719For the simplest code, use the :func: `dump ` and :func: `load ` functions. Note
722720that a self-referencing list is pickled and restored correctly. ::
723721
724722 import pickle
725723
726- data1 = {'a': [1, 2.0, 3, 4+6j],
727- 'b': ("string", "string using Unicode features \u0394"),
728- 'c': None}
729-
730- selfref_list = [1, 2, 3]
731- selfref_list.append(selfref_list)
732-
733- output = open('data.pkl', 'wb')
734-
735- # Pickle dictionary using protocol 2.
736- pickle.dump(data1, output, 2)
737-
738- # Pickle the list using the highest protocol available.
739- pickle.dump(selfref_list, output, -1)
740-
741- output.close()
724+ # An arbitrary collection of objects supported by pickle.
725+ data = {
726+ 'a': [1, 2.0, 3, 4+6j],
727+ 'b': ("character string", b"byte string"),
728+ 'c': set([None, True, False])
729+ }
742730
743- The following example reads the resulting pickled data. When reading a
744- pickle-containing file, you should open the file in binary mode because you
745- can't be sure if the ASCII or binary format was used. ::
731+ with open(' data.pickle', 'wb') as f:
732+ # Pickle the 'data' dictionary using the highest protocol available.
733+ pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
746734
747- import pprint, pickle
748735
749- pkl_file = open(' data.pkl', 'rb')
736+ The following example reads the resulting pickled data. ::
750737
751- data1 = pickle.load(pkl_file)
752- pprint.pprint(data1)
738+ import pickle
753739
754- data2 = pickle.load(pkl_file)
755- pprint.pprint(data2)
740+ with open('data.pickle', 'rb') as f:
741+ # The protocol version used is detected automatically, so we do not
742+ # have to specify it.
743+ data = pickle.load(f)
756744
757- pkl_file.close()
758745
759746.. seealso ::
760747
0 commit comments