home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / programming / python / pyhtml / pyhtmldoc / p / pickle < prev    next >
Encoding:
Text File  |  1996-11-14  |  9.5 KB  |  191 lines

  1. <TITLE>pickle -- Python library reference</TITLE>
  2. Next: <A HREF="../s/shelve" TYPE="Next">shelve</A>  
  3. Prev: <A HREF="../t/traceback" TYPE="Prev">traceback</A>  
  4. Up: <A HREF="../p/python_services" TYPE="Up">Python Services</A>  
  5. Top: <A HREF="../t/top" TYPE="Top">Top</A>  
  6. <H1>3.4. Standard Module <CODE>pickle</CODE></H1>
  7. The <CODE>pickle</CODE> module implements a basic but powerful algorithm for
  8. ``pickling'' (a.k.a. serializing, marshalling or flattening) nearly
  9. arbitrary Python objects.  This is the act of converting objects to a
  10. stream of bytes (and back: ``unpickling'').
  11. This is a more primitive notion than
  12. persistency --- although <CODE>pickle</CODE> reads and writes file objects,
  13. it does not handle the issue of naming persistent objects, nor the
  14. (even more complicated) area of concurrent access to persistent
  15. objects.  The <CODE>pickle</CODE> module can transform a complex object into
  16. a byte stream and it can transform the byte stream into an object with
  17. the same internal structure.  The most obvious thing to do with these
  18. byte streams is to write them onto a file, but it is also conceivable
  19. to send them across a network or store them in a database.  The module
  20. <CODE>shelve</CODE> provides a simple interface to pickle and unpickle
  21. objects on ``dbm''-style database files.
  22. Unlike the built-in module <CODE>marshal</CODE>, <CODE>pickle</CODE> handles the
  23. following correctly:
  24. <UL>
  25. <LI>•  recursive objects (objects containing references to themselves)
  26. <P>
  27. <LI>•  object sharing (references to the same object in different places)
  28. <P>
  29. <LI>•  user-defined classes and their instances
  30. <P>
  31. </UL>
  32. The data format used by <CODE>pickle</CODE> is Python-specific.  This has
  33. the advantage that there are no restrictions imposed by external
  34. standards such as CORBA (which probably can't represent pointer
  35. sharing or recursive objects); however it means that non-Python
  36. programs may not be able to reconstruct pickled Python objects.
  37. <P>
  38. The <CODE>pickle</CODE> data format uses a printable ASCII representation.
  39. This is slightly more voluminous than a binary representation.
  40. However, small integers actually take <I>less</I> space when
  41. represented as minimal-size decimal strings than when represented as
  42. 32-bit binary numbers, and strings are only much longer if they
  43. contain many control characters or 8-bit characters.  The big
  44. advantage of using printable ASCII (and of some other characteristics
  45. of <CODE>pickle</CODE>'s representation) is that for debugging or recovery
  46. purposes it is possible for a human to read the pickled file with a
  47. standard text editor.  (I could have gone a step further and used a
  48. notation like S-expressions, but the parser
  49. (currently written in Python) would have been
  50. considerably more complicated and slower, and the files would probably
  51. have become much larger.)
  52. <P>
  53. The <CODE>pickle</CODE> module doesn't handle code objects, which the
  54. <CODE>marshal</CODE> module does.  I suppose <CODE>pickle</CODE> could, and maybe
  55. it should, but there's probably no great need for it right now (as
  56. long as <CODE>marshal</CODE> continues to be used for reading and writing
  57. code objects), and at least this avoids the possibility of smuggling
  58. Trojan horses into a program.
  59. For the benefit of persistency modules written using <CODE>pickle</CODE>, it
  60. supports the notion of a reference to an object outside the pickled
  61. data stream.  Such objects are referenced by a name, which is an
  62. arbitrary string of printable ASCII characters.  The resolution of
  63. such names is not defined by the <CODE>pickle</CODE> module --- the
  64. persistent object module will have to implement a method
  65. <CODE>persistent_load</CODE>.  To write references to persistent objects,
  66. the persistent module must define a method <CODE>persistent_id</CODE> which
  67. returns either <CODE>None</CODE> or the persistent ID of the object.
  68. <P>
  69. There are some restrictions on the pickling of class instances.
  70. <P>
  71. First of all, the class must be defined at the top level in a module.
  72. <P>
  73. Next, it must normally be possible to create class instances by
  74. calling the class without arguments.  Usually, this is best
  75. accomplished by providing default values for all arguments to its
  76. <CODE>__init__</CODE> method (if it has one).  If this is undesirable, the
  77. class can define a method <CODE>__getinitargs__()</CODE>, which should
  78. return a <I>tuple</I> containing the arguments to be passed to the
  79. class constructor (<CODE>__init__()</CODE>).
  80. Classes can further influence how their instances are pickled --- if the class
  81. defines the method <CODE>__getstate__()</CODE>, it is called and the return
  82. state is pickled as the contents for the instance, and if the class
  83. defines the method <CODE>__setstate__()</CODE>, it is called with the
  84. unpickled state.  (Note that these methods can also be used to
  85. implement copying class instances.)  If there is no
  86. <CODE>__getstate__()</CODE> method, the instance's <CODE>__dict__</CODE> is
  87. pickled.  If there is no <CODE>__setstate__()</CODE> method, the pickled
  88. object must be a dictionary and its items are assigned to the new
  89. instance's dictionary.  (If a class defines both <CODE>__getstate__()</CODE>
  90. and <CODE>__setstate__()</CODE>, the state object needn't be a dictionary
  91. --- these methods can do what they want.)  This protocol is also used
  92. by the shallow and deep copying operations defined in the <CODE>copy</CODE>
  93. module.
  94. Note that when class instances are pickled, their class's code and
  95. data are not pickled along with them.  Only the instance data are
  96. pickled.  This is done on purpose, so you can fix bugs in a class or
  97. add methods and still load objects that were created with an earlier
  98. version of the class.  If you plan to have long-lived objects that
  99. will see many versions of a class, it may be worthwhile to put a version
  100. number in the objects so that suitable conversions can be made by the
  101. class's <CODE>__setstate__()</CODE> method.
  102. <P>
  103. When a class itself is pickled, only its name is pickled --- the class
  104. definition is not pickled, but re-imported by the unpickling process.
  105. Therefore, the restriction that the class must be defined at the top
  106. level in a module applies to pickled classes as well.
  107. <P>
  108. The interface can be summarized as follows.
  109. <P>
  110. To pickle an object <CODE>x</CODE> onto a file <CODE>f</CODE>, open for writing:
  111. <P>
  112. <UL COMPACT><CODE>p = pickle.Pickler(f)<P>
  113. p.dump(x)<P>
  114. </CODE></UL>
  115. A shorthand for this is:
  116. <P>
  117. <UL COMPACT><CODE>pickle.dump(x, f)<P>
  118. </CODE></UL>
  119. To unpickle an object <CODE>x</CODE> from a file <CODE>f</CODE>, open for reading:
  120. <P>
  121. <UL COMPACT><CODE>u = pickle.Unpickler(f)<P>
  122. x = u.load()<P>
  123. </CODE></UL>
  124. A shorthand is:
  125. <P>
  126. <UL COMPACT><CODE>x = pickle.load(f)<P>
  127. </CODE></UL>
  128. The <CODE>Pickler</CODE> class only calls the method <CODE>f.write</CODE> with a
  129. string argument.  The <CODE>Unpickler</CODE> calls the methods <CODE>f.read</CODE>
  130. (with an integer argument) and <CODE>f.readline</CODE> (without argument),
  131. both returning a string.  It is explicitly allowed to pass non-file
  132. objects here, as long as they have the right methods.
  133. The following types can be pickled:
  134. <UL>
  135. <LI>•  <CODE>None</CODE>
  136. <P>
  137. <LI>•  integers, long integers, floating point numbers
  138. <P>
  139. <LI>•  strings
  140. <P>
  141. <LI>•  tuples, lists and dictionaries containing only picklable objects
  142. <P>
  143. <LI>•  classes that are defined at the top level in a module
  144. <P>
  145. <LI>•  instances of such classes whose <CODE>__dict__</CODE> or
  146. <CODE>__setstate__()</CODE> is picklable
  147. <P>
  148. </UL>
  149. Attempts to pickle unpicklable objects will raise the
  150. <CODE>PicklingError</CODE> exception; when this happens, an unspecified
  151. number of bytes may have been written to the file.
  152. <P>
  153. It is possible to make multiple calls to the <CODE>dump()</CODE> method of
  154. the same <CODE>Pickler</CODE> instance.  These must then be matched to the
  155. same number of calls to the <CODE>load()</CODE> instance of the
  156. corresponding <CODE>Unpickler</CODE> instance.  If the same object is
  157. pickled by multiple <CODE>dump()</CODE> calls, the <CODE>load()</CODE> will all
  158. yield references to the same object.  <I>Warning</I>: this is intended
  159. for pickling multiple objects without intervening modifications to the
  160. objects or their parts.  If you modify an object and then pickle it
  161. again using the same <CODE>Pickler</CODE> instance, the object is not
  162. pickled again --- a reference to it is pickled and the
  163. <CODE>Unpickler</CODE> will return the old value, not the modified one.
  164. (There are two problems here: (a) detecting changes, and (b)
  165. marshalling a minimal set of changes.  I have no answers.  Garbage
  166. Collection may also become a problem here.)
  167. <P>
  168. Apart from the <CODE>Pickler</CODE> and <CODE>Unpickler</CODE> classes, the
  169. module defines the following functions, and an exception:
  170. <P>
  171. <DL><DT><B>dump</B> (<VAR>object</VAR>, <VAR>file</VAR>) -- function of module pickle<DD>
  172. Write a pickled representation of <VAR>obect</VAR> to the open file object
  173. <VAR>file</VAR>.  This is equivalent to <CODE>Pickler(file).dump(object)</CODE>.
  174. </DL>
  175. <DL><DT><B>load</B> (<VAR>file</VAR>) -- function of module pickle<DD>
  176. Read a pickled object from the open file object <VAR>file</VAR>.  This is
  177. equivalent to <CODE>Unpickler(file).load()</CODE>.
  178. </DL>
  179. <DL><DT><B>dumps</B> (<VAR>object</VAR>) -- function of module pickle<DD>
  180. Return the pickled representation of the object as a string, instead
  181. of writing it to a file.
  182. </DL>
  183. <DL><DT><B>loads</B> (<VAR>string</VAR>) -- function of module pickle<DD>
  184. Read a pickled object from a string instead of a file.  Characters in
  185. the string past the pickled object's representation are ignored.
  186. </DL>
  187. <DL><DT><B>PicklingError</B> -- exception of module pickle<DD>
  188. This exception is raised when an unpicklable object is passed to
  189. <CODE>Pickler.dump()</CODE>.
  190. </DL>
  191.