[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

new process, this difference is often irrelevant (though as we saw in Chapter 5, this
generally precludes using pickled objects directly as cross-process shared state).


Pickling works on almost any Python datatype—numbers, lists, dictionaries, class in-
stances, nested structures, and more—and so is a general way to store data. Because
pickles contain native Python objects, there is almost no database API to be found; the
objects stored with pickling are processed with normal Python syntax when they are
later retrieved.


Using Object Pickling


Pickling may sound complicated the first time you encounter it, but the good news is
that Python hides all the complexity of object-to-string conversion. In fact, the pickle
module ’s interfaces are incredibly simple to use. For example, to pickle an object into
a serialized string, we can either make a pickler and call its methods or use convenience
functions in the module to achieve the same effect:


P = pickle.Pickler(file)
Make a new pickler for pickling to an open output file object file.


P.dump(object )
Write an object onto the pickler’s file/stream.


pickle.dump(object, file)
Same as the last two calls combined: pickle an object onto an open file.


string = pickle.dumps(object)
Return the pickled representation of object as a character string.


Unpickling from a serialized string back to the original object is similar—both object
and convenience function interfaces are available:


U = pickle.Unpickler(file)
Make an unpickler for unpickling from an open input file object file.


object = U.load()
Read an object from the unpickler’s file/stream.


object = pickle.load(file)
Same as the last two calls combined: unpickle an object from an open file.


object = pickle.loads(string)
Read an object from a character string rather than a file.


Pickler and Unpickler are exported classes. In all of the preceding cases, file is either
an open file object or any object that implements the same attributes as file objects:



  • Pickler calls the file’s write method with a string argument.

  • Unpickler calls the file’s read method with a byte count, and readline without
    arguments.


1310 | Chapter 17: Databases and Persistence

Free download pdf