May 2001
Intermediate to advanced
304 pages
6h 12m
English
The copy_reg module provides a registry that you can use to register your own
extension types. The pickle and copy modules use this registry
to figure out how to process non-standard types.
For example, the standard pickle implementation cannot
deal with Python code objects, as shown in the following example:
File: copy-reg-example-1.py import pickle CODE = """ print 'good evening' """ code = compile(CODE, "<string>", "exec") exec code exec pickle.loads(pickle.dumps(code))good eveningTraceback (innermost last):...pickle.PicklingError: can't pickle 'code' objects
We can work around this by registering a code object handler. Such a handler consists of two parts: a pickler, which takes the code object and returns a tuple that can only contain simple datatypes, and an unpickler, which takes the contents of such a tuple as its arguments. Example 4-14 demonstrates this.
Example 4-14. Using the copy_reg Module to Enable Pickling of Code Objects
File: copy-reg-example-2.py
import copy_reg
import pickle, marshal, types
#
# register a pickle handler for code objects
def code_unpickler(data):
return marshal.loads(data)
def code_pickler(code):
return code_unpickler, (marshal.dumps(code),)
copy_reg.pickle(types.CodeType, code_pickler, code_unpickler)
#
# try it out
CODE = """
print "suppose he's got a pointed stick"
"""
code = compile(CODE, "<string>", "exec")
exec code
exec pickle.loads(pickle.dumps(code))
suppose he's got a pointed stick
suppose he's got a pointed stick ...Read now
Unlock full access