diff options
author | Andrew M. Kuchling <amk@amk.ca> | 2006-07-28 12:33:19 (GMT) |
---|---|---|
committer | Andrew M. Kuchling <amk@amk.ca> | 2006-07-28 12:33:19 (GMT) |
commit | bd468103e0f8649a600db0d02395fc600a4bd124 (patch) | |
tree | bd78ed9640d5f13530e2b4708719752172b06179 /Doc | |
parent | 4036f43cac3fdea22ec01c792df1701d17276e72 (diff) | |
download | cpython-bd468103e0f8649a600db0d02395fc600a4bd124.zip cpython-bd468103e0f8649a600db0d02395fc600a4bd124.tar.gz cpython-bd468103e0f8649a600db0d02395fc600a4bd124.tar.bz2 |
Add example
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/lib/libpickle.tex | 45 |
1 files changed, 44 insertions, 1 deletions
diff --git a/Doc/lib/libpickle.tex b/Doc/lib/libpickle.tex index 45e80b8..a8ab39e 100644 --- a/Doc/lib/libpickle.tex +++ b/Doc/lib/libpickle.tex @@ -725,7 +725,50 @@ source of the strings your application unpickles. \subsection{Example \label{pickle-example}} -Here's a simple example of how to modify pickling behavior for a +For the simplest code, use the \function{dump()} and \function{load()} +functions. Note that a self-referencing list is pickled and restored +correctly. + +\begin{verbatim} +import pickle + +data1 = {'a': [1, 2.0, 3, 4+6j], + 'b': ('string', u'Unicode string'), + 'c': None} + +selfref_list = [1, 2, 3] +selfref_list.append(selfref_list) + +output = open('data.pkl', 'wb') + +# Pickle dictionary using protocol 0. +pickle.dump(data1, output) + +# Pickle the list using the highest protocol available. +pickle.dump(selfref_list, output, -1) + +output.close() +\end{verbatim} + +The following example reads the resulting pickled data. When reading +a pickle-containing file, you should open the file in binary mode +because you can't be sure if the ASCII or binary format was used. + +\begin{verbatim} +import pprint, pickle + +pkl_file = open('data.pkl', 'rb') + +data1 = pickle.load(pkl_file) +pprint.pprint(data1) + +data2 = pickle.load(pkl_file) +pprint.pprint(data2) + +pkl_file.close() +\end{verbatim} + +Here's a larger example that shows how to modify pickling behavior for a class. The \class{TextReader} class opens a text file, and returns the line number and line contents each time its \method{readline()} method is called. If a \class{TextReader} instance is pickled, all |