\section{\module{pickle} --- Python object serialization} \declaremodule{standard}{pickle}\modulesynopsis{Convert Python objects to streams of bytes and back.}% Substantial improvements by Jim Kerr <jbkerr@sr.hp.com>.% Rewritten by Barry Warsaw <barry@zope.com> \index{persistence}\indexii{persistent}{objects}\indexii{serializing}{objects}\indexii{marshalling}{objects}\indexii{flattening}{objects}\indexii{pickling}{objects} The \module{pickle} module implements a fundamental, but powerfulalgorithm for serializing and de-serializing a Python objectstructure. ``Pickling'' is the process whereby a Python objecthierarchy is converted into a byte stream, and ``unpickling'' is theinverse operation, whereby a byte stream is converted back into anobject hierarchy. Pickling (and unpickling) is alternatively known as``serialization'', ``marshalling,''\footnote{Don't confuse this withthe \refmodule{marshal} module} or ``flattening'',however, to avoid confusion, the terms used here are ``pickling'' and``unpickling''. This documentation describes both the \module{pickle} module and the \refmodule{cPickle} module. \subsection{Relationship to other Python modules} The \module{pickle} module has an optimized cousin called the\module{cPickle} module. As its name implies, \module{cPickle} iswritten in C, so it can be up to 1000 times faster than\module{pickle}. However it does not support subclassing of the\function{Pickler()} and \function{Unpickler()} classes, because in\module{cPickle} these are functions, not classes. Most applicationshave no need for this functionality, and can benefit from the improvedperformance of \module{cPickle}. Other than that, the interfaces ofthe two modules are nearly identical; the common interface isdescribed in this manual and differences are pointed out wherenecessary. In the following discussions, we use the term ``pickle''to collectively describe the \module{pickle} and\module{cPickle} modules. The data streams the two modules produce are guaranteed to beinterchangeable. Python has a more primitive serialization module called\refmodule{marshal}, but in general\module{pickle} should always be the preferred way to serialize Pythonobjects. \module{marshal} exists primarily to support Python's\file{.pyc} files. The \module{pickle} module differs from \refmodule{marshal} severalsignificant ways: \begin{itemize} \item The \module{pickle} module keeps track of the objects it has already serialized, so that later references to the same object won't be serialized again. \module{marshal} doesn't do this. This has implications both for recursive objects and object sharing. Recursive objects are objects that contain references to themselves. These are not handled by marshal, and in fact, attempting to marshal recursive objects will crash your Python interpreter. Object sharing happens when there are multiple references to the same object in different places in the object hierarchy being serialized. \module{pickle} stores such objects only once, and ensures that all other references point to the master copy. Shared objects remain shared, which can be very important for mutable objects. \item \module{marshal} cannot be used to serialize user-defined classes and their instances. \module{pickle} can save and restore class instances transparently, however the class definition must be importable and live in the same module as when the object was stored. \item The \module{marshal} serialization format is not guaranteed to be portable across Python versions. Because its primary job in life is to support \file{.pyc} files, the Python implementers reserve the right to change the serialization format in non-backwards compatible ways should the need arise. The \module{pickle} serialization format is guaranteed to be backwards compatible across Python releases. \end{itemize} \begin{notice}[warning]The \module{pickle} module is not intended to be secure againsterroneous or maliciously constructed data. Never unpickle datareceived from an untrusted or unauthenticated source.\end{notice} Note that serialization is a more primitive notion than persistence;although\module{pickle} reads and writes file objects, it does not handle theissue of naming persistent objects, nor the (even more complicated)issue of concurrent access to persistent objects. The \module{pickle}module can transform a complex object into a byte stream and it cantransform the byte stream into an object with the same internalstructure. Perhaps the most obvious thing to do with these bytestreams is to write them onto a file, but it is also conceivable tosend them across a network or store them in a database. The module\refmodule{shelve} provides a simple interfaceto pickle and unpickle objects on DBM-style database files. \subsection{Data stream format} The data format used by \module{pickle} is Python-specific. This hasthe advantage that there are no restrictions imposed by externalstandards such as XDR\index{XDR}\index{External Data Representation}(which can't represent pointer sharing); however it means thatnon-Python programs may not be able to reconstruct pickled Pythonobjects. By default, the \module{pickle} data format uses a printable \ASCII{}representation. This is slightly more voluminous than a binaryrepresentation. The big advantage of using printable \ASCII{} (and ofsome other characteristics of \module{pickle}'s representation) is thatfor debugging or recovery purposes it is possible for a human to readthe pickled file with a standard text editor. There are currently 3 different protocols which can be used for pickling. \begin{itemize} \item Protocol version 0 is the original ASCII protocol and is backwardscompatible with earlier versions of Python. \item Protocol version 1 is the old binary format which is also compatiblewith earlier versions of Python. \item Protocol version 2 was introduced in Python 2.3. It providesmuch more efficient pickling of new-style classes. \end{itemize} Refer to PEP 307 for more information. If a \var{protocol} is not specified, protocol 0 is used.If \var{protocol} is specified as a negative valueor \constant{HIGHEST_PROTOCOL},the highest protocol version available will be used. \versionchanged[Introduced the \var{protocol} parameter]{2.3} A binary format, which is slightly more efficient, can be chosen byspecifying a \var{protocol} version >= 1. \subsection{Usage} To serialize an object hierarchy, you first create a pickler, then youcall the pickler's \method{dump()} method. To de-serialize a datastream, you first create an unpickler, then you call the unpickler's\method{load()} method. The \module{pickle} module provides thefollowing constant: \begin{datadesc}{HIGHEST_PROTOCOL}The highest protocol version available. This value can be passedas a \var{protocol} value.\versionadded{2.3}\end{datadesc} \note{Be sure to always open pickle files created with protocols >= 1 in binary mode. For the old ASCII-based pickle protocol 0 you can use either text mode or binary mode as long as you stay consistent. A pickle file written with protocol 0 in binary mode will contain lone linefeeds as line terminators and therefore will look ``funny'' when viewed in Notepad or other editors which do not support this format.} The \module{pickle} module provides thefollowing functions to make the pickling process more convenient: \begin{funcdesc}{dump}{obj, file\optional{, protocol}}Write a pickled representation of \var{obj} to the open file object\var{file}. This is equivalent to\code{Pickler(\var{file}, \var{protocol}).dump(\var{obj})}. If the \var{protocol} parameter is omitted, protocol 0 is used.If \var{protocol} is specified as a negative valueor \constant{HIGHEST_PROTOCOL},the highest protocol version will be used. \versionchanged[Introduced the \var{protocol} parameter]{2.3} \var{file} must have a \method{write()} method that accepts a singlestring argument. It can thus be a file object opened for writing, a\refmodule{StringIO} object, or any other customobject that meets this interface.\end{funcdesc} \begin{funcdesc}{load}{file}Read a string from the open file object \var{file} and interpret it asa pickle data stream, reconstructing and returning the original objecthierarchy. This is equivalent to \code{Unpickler(\var{file}).load()}. \var{file} must have two methods, a \method{read()} method that takesan integer argument, and a \method{readline()} method that requires noarguments. Both methods should return a string. Thus \var{file} canbe a file object opened for reading, a\module{StringIO} object, or any other customobject that meets this interface. This function automatically determines whether the data stream waswritten in binary mode or not.\end{funcdesc} \begin{funcdesc}{dumps}{obj\optional{, protocol}}Return the pickled representation of the object as a string, insteadof writing it to a file. If the \var{protocol} parameter is omitted, protocol 0 is used.If \var{protocol} is specified as a negative valueor \constant{HIGHEST_PROTOCOL},the highest protocol version will be used. \versionchanged[The \var{protocol} parameter was added]{2.3} \end{funcdesc} \begin{funcdesc}{loads}{string}Read a pickled object hierarchy from a string. Characters in thestring past the pickled object's representation are ignored.\end{funcdesc} The \module{pickle} module also defines three exceptions: \begin{excdesc}{PickleError}A common base class for the other exceptions defined below. Thisinherits from \exception{Exception}.\end{excdesc} \begin{excdesc}{PicklingError}This exception is raised when an unpicklable object is passed tothe \method{dump()} method.\end{excdesc} \begin{excdesc}{UnpicklingError}This exception is raised when there is a problem unpickling an object.Note that other exceptions may also be raised during unpickling,including (but not necessarily limited to) \exception{AttributeError},\exception{EOFError}, \exception{ImportError}, and \exception{IndexError}.\end{excdesc} The \module{pickle} module also exports two callables\footnote{In the\module{pickle} module these callables are classes, which you couldsubclass to customize the behavior. However, in the \refmodule{cPickle}module these callables are factory functions and so cannot besubclassed. One common reason to subclass is to control whatobjects can actually be unpickled. See section~\ref{pickle-sub} formore details.}, \class{Pickler} and \class{Unpickler}: \begin{classdesc}{Pickler}{file\optional{, protocol}}This takes a file-like object to which it will write a pickle datastream. If the \var{protocol} parameter is omitted, protocol 0 is used.If \var{protocol} is specified as a negative value,the highest protocol version will be used. \versionchanged[Introduced the \var{protocol} parameter]{2.3} \var{file} must have a \method{write()} method that accepts a singlestring argument. It can thus be an open file object, a\module{StringIO} object, or any other customobject that meets this interface.\end{classdesc} \class{Pickler} objects define one (or two) public methods: \begin{methoddesc}[Pickler]{dump}{obj}Write a pickled representation of \var{obj} to the open file objectgiven in the constructor. Either the binary or \ASCII{} format willbe used, depending on the value of the \var{protocol} argument passed to theconstructor.\end{methoddesc} \begin{methoddesc}[Pickler]{clear_memo}{}Clears the pickler's ``memo''. The memo is the data structure thatremembers which objects the pickler has already seen, so that sharedor recursive objects pickled by reference and not by value. Thismethod is useful when re-using picklers. \begin{notice}Prior to Python 2.3, \method{clear_memo()} was only available on thepicklers created by \refmodule{cPickle}. In the \module{pickle} module,picklers have an instance variable called \member{memo} which is aPython dictionary. So to clear the memo for a \module{pickle} modulepickler, you could do the following: \begin{verbatim}mypickler.memo.clear()\end{verbatim} Code that does not need to support older versions of Python shouldsimply use \method{clear_memo()}.\end{notice}\end{methoddesc} It is possible to make multiple calls to the \method{dump()} method ofthe same \class{Pickler} instance. These must then be matched to thesame number of calls to the \method{load()} method of thecorresponding \class{Unpickler} instance. If the same object ispickled by multiple \method{dump()} calls, the \method{load()} willall yield references to the same object.\footnote{\emph{Warning}: thisis intended for pickling multiple objects without interveningmodifications to the objects or their parts. If you modify an objectand then pickle it again using the same \class{Pickler} instance, theobject is not pickled again --- a reference to it is pickled and the\class{Unpickler} will return the old value, not the modified one.There are two problems here: (1) detecting changes, and (2)marshalling a minimal set of changes. Garbage Collection may alsobecome a problem here.} \class{Unpickler} objects are defined as: \begin{classdesc}{Unpickler}{file}This takes a file-like object from which it will read a pickle datastream. This class automatically determines whether the data streamwas written in binary mode or not, so it does not need a flag as inthe \class{Pickler} factory. \var{file} must have two methods, a \method{read()} method that takesan integer argument, and a \method{readline()} method that requires noarguments. Both methods should return a string. Thus \var{file} canbe a file object opened for reading, a\module{StringIO} object, or any other customobject that meets this interface.\end{classdesc} \class{Unpickler} objects have one (or two) public methods: \begin{methoddesc}[Unpickler]{load}{}Read a pickled object representation from the open file object givenin the constructor, and return the reconstituted object hierarchyspecified therein.\end{methoddesc} \begin{methoddesc}[Unpickler]{noload}{}This is just like \method{load()} except that it doesn't actuallycreate any objects. This is useful primarily for finding what'scalled ``persistent ids'' that may be referenced in a pickle datastream. See section~\ref{pickle-protocol} below for more details. \strong{Note:} the \method{noload()} method is currently onlyavailable on \class{Unpickler} objects created with the\module{cPickle} module. \module{pickle} module \class{Unpickler}s donot have the \method{noload()} method.\end{methoddesc} \subsection{What can be pickled and unpickled?} The following types can be pickled: \begin{itemize} \item \code{None}, \code{True}, and \code{False} \item integers, long integers, floating point numbers, complex numbers \item normal and Unicode strings \item tuples, lists, sets, and dictionaries containing only picklable objects \item functions defined at the top level of a module \item built-in functions defined at the top level of a module \item classes that are defined at the top level of a module \item instances of such classes whose \member{__dict__} or\method{__setstate__()} is picklable (seesection~\ref{pickle-protocol} for details) \end{itemize} Attempts to pickle unpicklable objects will raise the\exception{PicklingError} exception; when this happens, an unspecifiednumber of bytes may have already been written to the underlying file.Trying to pickle a highly recursive data structure may exceed themaximum recursion depth, a \exception{RuntimeError} will be raisedin this case. You can carefully raise this limit with \function{sys.setrecursionlimit()}. Note that functions (built-in and user-defined) are pickled by ``fullyqualified'' name reference, not by value. This means that only thefunction name is pickled, along with the name of module the functionis defined in. Neither the function's code, nor any of its functionattributes are pickled. Thus the defining module must be importablein the unpickling environment, and the module must contain the namedobject, otherwise an exception will be raised.\footnote{The exceptionraised will likely be an \exception{ImportError} or an\exception{AttributeError} but it could be something else.} Similarly, classes are pickled by named reference, so the samerestrictions in the unpickling environment apply. Note that none ofthe class's code or data is pickled, so in the following example theclass attribute \code{attr} is not restored in the unpicklingenvironment: \begin{verbatim}class Foo: attr = 'a class attr' picklestring = pickle.dumps(Foo)\end{verbatim} These restrictions are why picklable functions and classes must bedefined in the top level of a module. Similarly, when class instances are pickled, their class's code anddata are not pickled along with them. Only the instance data arepickled. This is done on purpose, so you can fix bugs in a class oradd methods to the class and still load objects that were created withan earlier version of the class. If you plan to have long-livedobjects that will see many versions of a class, it may be worthwhileto put a version number in the objects so that suitable conversionscan be made by the class's \method{__setstate__()} method. \subsection{The pickle protocol\label{pickle-protocol}}\setindexsubitem{(pickle protocol)} This section describes the ``pickling protocol'' that defines theinterface between the pickler/unpickler and the objects that are beingserialized. This protocol provides a standard way for you to define,customize, and control how your objects are serialized andde-serialized. The description in this section doesn't cover specificcustomizations that you can employ to make the unpickling environmentslightly safer from untrusted pickle data streams; see section~\ref{pickle-sub}for more details. \subsubsection{Pickling and unpickling normal class instances\label{pickle-inst}} When a pickled class instance is unpickled, its \method{__init__()}method is normally \emph{not} invoked. If it is desirable that the\method{__init__()} method be called on unpickling, an old-style classcan define a method \method{__getinitargs__()}, which should return a\emph{tuple} containing the arguments to be passed to the classconstructor (\method{__init__()} for example). The\method{__getinitargs__()} method is called atpickle time; the tuple it returns is incorporated in the pickle forthe instance.\withsubitem{(copy protocol)}{\ttindex{__getinitargs__()}}\withsubitem{(instance constructor)}{\ttindex{__init__()}} \withsubitem{(copy protocol)}{\ttindex{__getnewargs__()}} New-style types can provide a \method{__getnewargs__()} method that isused for protocol 2. Implementing this method is needed if the typeestablishes some internal invariants when the instance is created, orif the memory allocation is affected by the values passed to the\method{__new__()} method for the type (as it is for tuples andstrings). Instances of a new-style type \class{C} are created using \begin{alltt}obj = C.__new__(C, *\var{args})\end{alltt} where \var{args} is the result of calling \method{__getnewargs__()} onthe original object; if there is no \method{__getnewargs__()}, anempty tuple is assumed. \withsubitem{(copy protocol)}{ \ttindex{__getstate__()}\ttindex{__setstate__()}}\withsubitem{(instance attribute)}{ \ttindex{__dict__}} Classes can further influence how their instances are pickled; if theclass defines the method \method{__getstate__()}, it is called and thereturn state is pickled as the contents for the instance, instead ofthe contents of the instance's dictionary. If there is no\method{__getstate__()} method, the instance's \member{__dict__} ispickled. Upon unpickling, if the class also defines the method\method{__setstate__()}, it is called with the unpickledstate.\footnote{These methods can also be used to implement copyingclass instances.} If there is no \method{__setstate__()} method, thepickled state must be a dictionary and its items are assigned to thenew instance's dictionary. If a class defines both\method{__getstate__()} and \method{__setstate__()}, the state objectneedn't be a dictionary and these methods can do what theywant.\footnote{This protocol is also used by the shallow and deepcopying operations defined in the\refmodule{copy} module.} \begin{notice}[warning] For new-style classes, if \method{__getstate__()} returns a false value, the \method{__setstate__()} method will not be called.\end{notice} \subsubsection{Pickling and unpickling extension types} When the \class{Pickler} encounters an object of a type it knowsLines 1–500 of 888. Load more
\section{\module{pickle} --- Python object serialization} \declaremodule{standard}{pickle} \modulesynopsis{Convert Python objects to streams of bytes and back.} % Substantial improvements by Jim Kerr <jbkerr@sr.hp.com>. % Rewritten by Barry Warsaw <barry@zope.com> \index{persistence} \indexii{persistent}{objects} \indexii{serializing}{objects} \indexii{marshalling}{objects} \indexii{flattening}{objects} \indexii{pickling}{objects} The \module{pickle} module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. ``Pickling'' is the process whereby a Python object hierarchy is converted into a byte stream, and ``unpickling'' is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as ``serialization'', ``marshalling,''\footnote{Don't confuse this with the \refmodule{marshal} module} or ``flattening'', however, to avoid confusion, the terms used here are ``pickling'' and ``unpickling''. This documentation describes both the \module{pickle} module and the \refmodule{cPickle} module. \subsection{Relationship to other Python modules} The \module{pickle} module has an optimized cousin called the \module{cPickle} module. As its name implies, \module{cPickle} is written in C, so it can be up to 1000 times faster than \module{pickle}. However it does not support subclassing of the \function{Pickler()} and \function{Unpickler()} classes, because in \module{cPickle} these are functions, not classes. Most applications have no need for this functionality, and can benefit from the improved performance of \module{cPickle}. Other than that, the interfaces of the two modules are nearly identical; the common interface is described in this manual and differences are pointed out where necessary. In the following discussions, we use the term ``pickle'' to collectively describe the \module{pickle} and \module{cPickle} modules. The data streams the two modules produce are guaranteed to be interchangeable. Python has a more primitive serialization module called \refmodule{marshal}, but in general \module{pickle} should always be the preferred way to serialize Python objects. \module{marshal} exists primarily to support Python's \file{.pyc} files. The \module{pickle} module differs from \refmodule{marshal} several significant ways: \begin{itemize} \item The \module{pickle} module keeps track of the objects it has already serialized, so that later references to the same object won't be serialized again. \module{marshal} doesn't do this. This has implications both for recursive objects and object sharing. Recursive objects are objects that contain references to themselves. These are not handled by marshal, and in fact, attempting to marshal recursive objects will crash your Python interpreter. Object sharing happens when there are multiple references to the same object in different places in the object hierarchy being serialized. \module{pickle} stores such objects only once, and ensures that all other references point to the master copy. Shared objects remain shared, which can be very important for mutable objects. \item \module{marshal} cannot be used to serialize user-defined classes and their instances. \module{pickle} can save and restore class instances transparently, however the class definition must be importable and live in the same module as when the object was stored. \item The \module{marshal} serialization format is not guaranteed to be portable across Python versions. Because its primary job in life is to support \file{.pyc} files, the Python implementers reserve the right to change the serialization format in non-backwards compatible ways should the need arise. The \module{pickle} serialization format is guaranteed to be backwards compatible across Python releases. \end{itemize} \begin{notice}[warning] The \module{pickle} module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source. \end{notice} Note that serialization is a more primitive notion than persistence; although \module{pickle} reads and writes file objects, it does not handle the issue of naming persistent objects, nor the (even more complicated) issue of concurrent access to persistent objects. The \module{pickle} module can transform a complex object into a byte stream and it can transform the byte stream into an object with the same internal structure. Perhaps the most obvious thing to do with these byte streams is to write them onto a file, but it is also conceivable to send them across a network or store them in a database. The module \refmodule{shelve} provides a simple interface to pickle and unpickle objects on DBM-style database files. \subsection{Data stream format} The data format used by \module{pickle} is Python-specific. This has the advantage that there are no restrictions imposed by external standards such as XDR\index{XDR}\index{External Data Representation} (which can't represent pointer sharing); however it means that non-Python programs may not be able to reconstruct pickled Python objects. By default, the \module{pickle} data format uses a printable \ASCII{} representation. This is slightly more voluminous than a binary representation. The big advantage of using printable \ASCII{} (and of some other characteristics of \module{pickle}'s representation) is that for debugging or recovery purposes it is possible for a human to read the pickled file with a standard text editor. There are currently 3 different protocols which can be used for pickling. \begin{itemize} \item Protocol version 0 is the original ASCII protocol and is backwards compatible with earlier versions of Python. \item Protocol version 1 is the old binary format which is also compatible with earlier versions of Python. \item Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. \end{itemize} Refer to PEP 307 for more information. If a \var{protocol} is not specified, protocol 0 is used. If \var{protocol} is specified as a negative value or \constant{HIGHEST_PROTOCOL}, the highest protocol version available will be used. \versionchanged[Introduced the \var{protocol} parameter]{2.3} A binary format, which is slightly more efficient, can be chosen by specifying a \var{protocol} version >= 1. \subsection{Usage} To serialize an object hierarchy, you first create a pickler, then you call the pickler's \method{dump()} method. To de-serialize a data stream, you first create an unpickler, then you call the unpickler's \method{load()} method. The \module{pickle} module provides the following constant: \begin{datadesc}{HIGHEST_PROTOCOL} The highest protocol version available. This value can be passed as a \var{protocol} value. \versionadded{2.3} \end{datadesc} \note{Be sure to always open pickle files created with protocols >= 1 in binary mode. For the old ASCII-based pickle protocol 0 you can use either text mode or binary mode as long as you stay consistent. A pickle file written with protocol 0 in binary mode will contain lone linefeeds as line terminators and therefore will look ``funny'' when viewed in Notepad or other editors which do not support this format.} The \module{pickle} module provides the following functions to make the pickling process more convenient: \begin{funcdesc}{dump}{obj, file\optional{, protocol}} Write a pickled representation of \var{obj} to the open file object \var{file}. This is equivalent to \code{Pickler(\var{file}, \var{protocol}).dump(\var{obj})}. If the \var{protocol} parameter is omitted, protocol 0 is used. If \var{protocol} is specified as a negative value or \constant{HIGHEST_PROTOCOL}, the highest protocol version will be used. \versionchanged[Introduced the \var{protocol} parameter]{2.3} \var{file} must have a \method{write()} method that accepts a single string argument. It can thus be a file object opened for writing, a \refmodule{StringIO} object, or any other custom object that meets this interface. \end{funcdesc} \begin{funcdesc}{load}{file} Read a string from the open file object \var{file} and interpret it as a pickle data stream, reconstructing and returning the original object hierarchy. This is equivalent to \code{Unpickler(\var{file}).load()}. \var{file} must have two methods, a \method{read()} method that takes an integer argument, and a \method{readline()} method that requires no arguments. Both methods should return a string. Thus \var{file} can be a file object opened for reading, a \module{StringIO} object, or any other custom object that meets this interface. This function automatically determines whether the data stream was written in binary mode or not. \end{funcdesc} \begin{funcdesc}{dumps}{obj\optional{, protocol}} Return the pickled representation of the object as a string, instead of writing it to a file. If the \var{protocol} parameter is omitted, protocol 0 is used. If \var{protocol} is specified as a negative value or \constant{HIGHEST_PROTOCOL}, the highest protocol version will be used. \versionchanged[The \var{protocol} parameter was added]{2.3} \end{funcdesc} \begin{funcdesc}{loads}{string} Read a pickled object hierarchy from a string. Characters in the string past the pickled object's representation are ignored. \end{funcdesc} The \module{pickle} module also defines three exceptions: \begin{excdesc}{PickleError} A common base class for the other exceptions defined below. This inherits from \exception{Exception}. \end{excdesc} \begin{excdesc}{PicklingError} This exception is raised when an unpicklable object is passed to the \method{dump()} method. \end{excdesc} \begin{excdesc}{UnpicklingError} This exception is raised when there is a problem unpickling an object. Note that other exceptions may also be raised during unpickling, including (but not necessarily limited to) \exception{AttributeError}, \exception{EOFError}, \exception{ImportError}, and \exception{IndexError}. \end{excdesc} The \module{pickle} module also exports two callables\footnote{In the \module{pickle} module these callables are classes, which you could subclass to customize the behavior. However, in the \refmodule{cPickle} module these callables are factory functions and so cannot be subclassed. One common reason to subclass is to control what objects can actually be unpickled. See section~\ref{pickle-sub} for more details.}, \class{Pickler} and \class{Unpickler}: \begin{classdesc}{Pickler}{file\optional{, protocol}} This takes a file-like object to which it will write a pickle data stream. If the \var{protocol} parameter is omitted, protocol 0 is used. If \var{protocol} is specified as a negative value, the highest protocol version will be used. \versionchanged[Introduced the \var{protocol} parameter]{2.3} \var{file} must have a \method{write()} method that accepts a single string argument. It can thus be an open file object, a \module{StringIO} object, or any other custom object that meets this interface. \end{classdesc} \class{Pickler} objects define one (or two) public methods: \begin{methoddesc}[Pickler]{dump}{obj} Write a pickled representation of \var{obj} to the open file object given in the constructor. Either the binary or \ASCII{} format will be used, depending on the value of the \var{protocol} argument passed to the constructor. \end{methoddesc} \begin{methoddesc}[Pickler]{clear_memo}{} Clears the pickler's ``memo''. The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects pickled by reference and not by value. This method is useful when re-using picklers. \begin{notice} Prior to Python 2.3, \method{clear_memo()} was only available on the picklers created by \refmodule{cPickle}. In the \module{pickle} module, picklers have an instance variable called \member{memo} which is a Python dictionary. So to clear the memo for a \module{pickle} module pickler, you could do the following: \begin{verbatim} mypickler.memo.clear() \end{verbatim} Code that does not need to support older versions of Python should simply use \method{clear_memo()}. \end{notice} \end{methoddesc} It is possible to make multiple calls to the \method{dump()} method of the same \class{Pickler} instance. These must then be matched to the same number of calls to the \method{load()} method of the corresponding \class{Unpickler} instance. If the same object is pickled by multiple \method{dump()} calls, the \method{load()} will all yield references to the same object.\footnote{\emph{Warning}: this is intended for pickling multiple objects without intervening modifications to the objects or their parts. If you modify an object and then pickle it again using the same \class{Pickler} instance, the object is not pickled again --- a reference to it is pickled and the \class{Unpickler} will return the old value, not the modified one. There are two problems here: (1) detecting changes, and (2) marshalling a minimal set of changes. Garbage Collection may also become a problem here.} \class{Unpickler} objects are defined as: \begin{classdesc}{Unpickler}{file} This takes a file-like object from which it will read a pickle data stream. This class automatically determines whether the data stream was written in binary mode or not, so it does not need a flag as in the \class{Pickler} factory. \var{file} must have two methods, a \method{read()} method that takes an integer argument, and a \method{readline()} method that requires no arguments. Both methods should return a string. Thus \var{file} can be a file object opened for reading, a \module{StringIO} object, or any other custom object that meets this interface. \end{classdesc} \class{Unpickler} objects have one (or two) public methods: \begin{methoddesc}[Unpickler]{load}{} Read a pickled object representation from the open file object given in the constructor, and return the reconstituted object hierarchy specified therein. \end{methoddesc} \begin{methoddesc}[Unpickler]{noload}{} This is just like \method{load()} except that it doesn't actually create any objects. This is useful primarily for finding what's called ``persistent ids'' that may be referenced in a pickle data stream. See section~\ref{pickle-protocol} below for more details. \strong{Note:} the \method{noload()} method is currently only available on \class{Unpickler} objects created with the \module{cPickle} module. \module{pickle} module \class{Unpickler}s do not have the \method{noload()} method. \end{methoddesc} \subsection{What can be pickled and unpickled?} The following types can be pickled: \begin{itemize} \item \code{None}, \code{True}, and \code{False} \item integers, long integers, floating point numbers, complex numbers \item normal and Unicode strings \item tuples, lists, sets, and dictionaries containing only picklable objects \item functions defined at the top level of a module \item built-in functions defined at the top level of a module \item classes that are defined at the top level of a module \item instances of such classes whose \member{__dict__} or \method{__setstate__()} is picklable (see section~\ref{pickle-protocol} for details) \end{itemize} Attempts to pickle unpicklable objects will raise the \exception{PicklingError} exception; when this happens, an unspecified number of bytes may have already been written to the underlying file. Trying to pickle a highly recursive data structure may exceed the maximum recursion depth, a \exception{RuntimeError} will be raised in this case. You can carefully raise this limit with \function{sys.setrecursionlimit()}. Note that functions (built-in and user-defined) are pickled by ``fully qualified'' name reference, not by value. This means that only the function name is pickled, along with the name of module the function is defined in. Neither the function's code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised.\footnote{The exception raised will likely be an \exception{ImportError} or an \exception{AttributeError} but it could be something else.} Similarly, classes are pickled by named reference, so the same restrictions in the unpickling environment apply. Note that none of the class's code or data is pickled, so in the following example the class attribute \code{attr} is not restored in the unpickling environment: \begin{verbatim} class Foo: attr = 'a class attr' picklestring = pickle.dumps(Foo) \end{verbatim} These restrictions are why picklable functions and classes must be defined in the top level of a module. Similarly, when class instances are pickled, their class's code and data are not pickled along with them. Only the instance data are pickled. This is done on purpose, so you can fix bugs in a class or add methods to the class and still load objects that were created with an earlier version of the class. If you plan to have long-lived objects that will see many versions of a class, it may be worthwhile to put a version number in the objects so that suitable conversions can be made by the class's \method{__setstate__()} method. \subsection{The pickle protocol \label{pickle-protocol}}\setindexsubitem{(pickle protocol)} This section describes the ``pickling protocol'' that defines the interface between the pickler/unpickler and the objects that are being serialized. This protocol provides a standard way for you to define, customize, and control how your objects are serialized and de-serialized. The description in this section doesn't cover specific customizations that you can employ to make the unpickling environment slightly safer from untrusted pickle data streams; see section~\ref{pickle-sub} for more details. \subsubsection{Pickling and unpickling normal class instances\label{pickle-inst}} When a pickled class instance is unpickled, its \method{__init__()} method is normally \emph{not} invoked. If it is desirable that the \method{__init__()} method be called on unpickling, an old-style class can define a method \method{__getinitargs__()}, which should return a \emph{tuple} containing the arguments to be passed to the class constructor (\method{__init__()} for example). The \method{__getinitargs__()} method is called at pickle time; the tuple it returns is incorporated in the pickle for the instance. \withsubitem{(copy protocol)}{\ttindex{__getinitargs__()}} \withsubitem{(instance constructor)}{\ttindex{__init__()}} \withsubitem{(copy protocol)}{\ttindex{__getnewargs__()}} New-style types can provide a \method{__getnewargs__()} method that is used for protocol 2. Implementing this method is needed if the type establishes some internal invariants when the instance is created, or if the memory allocation is affected by the values passed to the \method{__new__()} method for the type (as it is for tuples and strings). Instances of a new-style type \class{C} are created using \begin{alltt} obj = C.__new__(C, *\var{args}) \end{alltt} where \var{args} is the result of calling \method{__getnewargs__()} on the original object; if there is no \method{__getnewargs__()}, an empty tuple is assumed. \withsubitem{(copy protocol)}{ \ttindex{__getstate__()}\ttindex{__setstate__()}} \withsubitem{(instance attribute)}{ \ttindex{__dict__}} Classes can further influence how their instances are pickled; if the class defines the method \method{__getstate__()}, it is called and the return state is pickled as the contents for the instance, instead of the contents of the instance's dictionary. If there is no \method{__getstate__()} method, the instance's \member{__dict__} is pickled. Upon unpickling, if the class also defines the method \method{__setstate__()}, it is called with the unpickled state.\footnote{These methods can also be used to implement copying class instances.} If there is no \method{__setstate__()} method, the pickled state must be a dictionary and its items are assigned to the new instance's dictionary. If a class defines both \method{__getstate__()} and \method{__setstate__()}, the state object needn't be a dictionary and these methods can do what they want.\footnote{This protocol is also used by the shallow and deep copying operations defined in the \refmodule{copy} module.} \begin{notice}[warning] For new-style classes, if \method{__getstate__()} returns a false value, the \method{__setstate__()} method will not be called. \end{notice} \subsubsection{Pickling and unpickling extension types} When the \class{Pickler} encounters an object of a type it knows