Fix the availability statement for the spawn*() functions to reflect the
[python/dscho.git] / Lib / copy_reg.py
blob92cbd5345b7163995ccb2961c1183fc9af7e4460
1 """Helper to provide extensibility for pickle/cPickle.
3 This is only useful to add pickle support for extension types defined in
4 C, not for instances of user-defined classes.
5 """
7 from types import ClassType as _ClassType
9 __all__ = ["pickle","constructor"]
11 dispatch_table = {}
12 safe_constructors = {}
14 def pickle(ob_type, pickle_function, constructor_ob=None):
15 if type(ob_type) is _ClassType:
16 raise TypeError("copy_reg is not intended for use with classes")
18 if not callable(pickle_function):
19 raise TypeError("reduction functions must be callable")
20 dispatch_table[ob_type] = pickle_function
22 if constructor_ob is not None:
23 constructor(constructor_ob)
25 def constructor(object):
26 if not callable(object):
27 raise TypeError("constructors must be callable")
28 safe_constructors[object] = 1
30 # Example: provide pickling support for complex numbers.
32 def pickle_complex(c):
33 return complex, (c.real, c.imag)
35 pickle(type(1j), pickle_complex, complex)
37 # Support for picking new-style objects
39 def _reconstructor(cls, base, state):
40 obj = base.__new__(cls, state)
41 base.__init__(obj, state)
42 return obj
43 _reconstructor.__safe_for_unpickling__ = 1
45 _HEAPTYPE = 1<<9
47 def _reduce(self):
48 for base in self.__class__.__mro__:
49 if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
50 break
51 else:
52 base = object # not really reachable
53 if base is object:
54 state = None
55 else:
56 state = base(self)
57 args = (self.__class__, base, state)
58 try:
59 getstate = self.__getstate__
60 except AttributeError:
61 try:
62 dict = self.__dict__
63 except AttributeError:
64 dict = None
65 else:
66 dict = getstate()
67 if dict:
68 return _reconstructor, args, dict
69 else:
70 return _reconstructor, args