ยปCore Development>Code coverage>Lib/copy_reg.py

Python code coverage for Lib/copy_reg.py

#countcontent
1n/a"""Helper to provide extensibility for pickle/cPickle.
2n/a
3n/aThis is only useful to add pickle support for extension types defined in
4n/aC, not for instances of user-defined classes.
5n/a"""
6n/a
70from types import ClassType as _ClassType
8n/a
90__all__ = ["pickle", "constructor",
100 "add_extension", "remove_extension", "clear_extension_cache"]
11n/a
120dispatch_table = {}
13n/a
140def pickle(ob_type, pickle_function, constructor_ob=None):
1510 if type(ob_type) is _ClassType:
161 raise TypeError("copy_reg is not intended for use with classes")
17n/a
189 if not hasattr(pickle_function, '__call__'):
191 raise TypeError("reduction functions must be callable")
208 dispatch_table[ob_type] = pickle_function
21n/a
22n/a # The constructor_ob function is a vestige of safe for unpickling.
23n/a # There is no reason for the caller to pass it anymore.
248 if constructor_ob is not None:
258 constructor(constructor_ob)
26n/a
270def constructor(object):
288 if not hasattr(object, '__call__'):
291 raise TypeError("constructors must be callable")
30n/a
31n/a# Example: provide pickling support for complex numbers.
32n/a
330try:
340 complex
350except NameError:
360 pass
37n/aelse:
38n/a
390 def pickle_complex(c):
4045 return complex, (c.real, c.imag)
41n/a
420 pickle(complex, pickle_complex, complex)
43n/a
44n/a# Support for pickling new-style objects
45n/a
460def _reconstructor(cls, base, state):
47457 if base is object:
48148 obj = object.__new__(cls)
49n/a else:
50309 obj = base.__new__(cls, state)
51309 if base.__init__ != object.__init__:
52139 base.__init__(obj, state)
53457 return obj
54n/a
550_HEAPTYPE = 1<<9
56n/a
57n/a# Python code for object.__reduce_ex__ for protocols 0 and 1
58n/a
590def _reduce_ex(self, proto):
60658 assert proto < 2
611413 for base in self.__class__.__mro__:
621413 if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
63658 break
64n/a else:
650 base = object # not really reachable
66658 if base is object:
67349 state = None
68n/a else:
69309 if base is self.__class__:
700 raise TypeError, "can't pickle %s objects" % base.__name__
71309 state = base(self)
72658 args = (self.__class__, base, state)
73658 try:
74658 getstate = self.__getstate__
75614 except AttributeError:
76614 if getattr(self, "__slots__", None):
778 raise TypeError("a class that defines __slots__ without "
78n/a "defining __getstate__ cannot be pickled")
79606 try:
80606 dict = self.__dict__
814 except AttributeError:
824 dict = None
83n/a else:
8444 dict = getstate()
85650 if dict:
86618 return _reconstructor, args, dict
87n/a else:
8832 return _reconstructor, args
89n/a
90n/a# Helper for __reduce_ex__ protocol 2
91n/a
920def __newobj__(cls, *args):
93368 return cls.__new__(cls, *args)
94n/a
950def _slotnames(cls):
96n/a """Return a list of slot names for a given class.
97n/a
98n/a This needs to find slots defined by the class and its bases, so we
99n/a can't simply return the __slots__ attribute. We must walk down
100n/a the Method Resolution Order and concatenate the __slots__ of each
101n/a class found there. (This assumes classes don't modify their
102n/a __slots__ attribute to misrepresent their slots after the class is
103n/a defined.)
104n/a """
105n/a
106n/a # Get the value from a cache in the class if possible
10796 names = cls.__dict__.get("__slotnames__")
10896 if names is not None:
1090 return names
110n/a
111n/a # Not cached -- calculate the value
11296 names = []
11396 if not hasattr(cls, "__slots__"):
114n/a # This class has no slots
11585 pass
116n/a else:
117n/a # Slots found -- gather slot names from all base classes
11843 for c in cls.__mro__:
11932 if "__slots__" in c.__dict__:
12012 slots = c.__dict__['__slots__']
121n/a # if class has a single slot, it can be given as a string
12212 if isinstance(slots, basestring):
1232 slots = (slots,)
12423 for name in slots:
125n/a # special descriptors
12611 if name in ("__dict__", "__weakref__"):
1271 continue
128n/a # mangled names
12910 elif name.startswith('__') and not name.endswith('__'):
1301 names.append('_%s%s' % (c.__name__, name))
131n/a else:
1329 names.append(name)
133n/a
134n/a # Cache the outcome in the class if at all possible
13596 try:
13696 cls.__slotnames__ = names
13714 except:
13814 pass # But don't die if we can't
139n/a
14096 return names
141n/a
142n/a# A registry of extension codes. This is an ad-hoc compression
143n/a# mechanism. Whenever a global reference to <module>, <name> is about
144n/a# to be pickled, the (<module>, <name>) tuple is looked up here to see
145n/a# if it is a registered extension code for it. Extension codes are
146n/a# universal, so that the meaning of a pickle does not depend on
147n/a# context. (There are also some codes reserved for local use that
148n/a# don't have this restriction.) Codes are positive ints; 0 is
149n/a# reserved.
150n/a
1510_extension_registry = {} # key -> code
1520_inverted_registry = {} # code -> key
1530_extension_cache = {} # code -> object
154n/a# Don't ever rebind those names: cPickle grabs a reference to them when
155n/a# it's initialized, and won't see a rebinding.
156n/a
1570def add_extension(module, name, code):
158n/a """Register an extension code."""
15982 code = int(code)
16082 if not 1 <= code <= 0x7fffffff:
1613 raise ValueError, "code out of range"
16279 key = (module, name)
16379 if (_extension_registry.get(key) == code and
1641 _inverted_registry.get(code) == key):
1651 return # Redundant registrations are benign
16678 if key in _extension_registry:
1671 raise ValueError("key %s is already registered with code %s" %
1681 (key, _extension_registry[key]))
16977 if code in _inverted_registry:
1702 raise ValueError("code %s is already in use for key %s" %
1712 (code, _inverted_registry[code]))
17275 _extension_registry[key] = code
17375 _inverted_registry[code] = key
174n/a
1750def remove_extension(module, name, code):
176n/a """Unregister an extension code. For testing only."""
17780 key = (module, name)
17880 if (_extension_registry.get(key) != code or
17975 _inverted_registry.get(code) != key):
1805 raise ValueError("key %s is not registered with code %s" %
1815 (key, code))
18275 del _extension_registry[key]
18375 del _inverted_registry[code]
18475 if code in _extension_cache:
18572 del _extension_cache[code]
186n/a
1870def clear_extension_cache():
1880 _extension_cache.clear()
189n/a
190n/a# Standard extension code assignments
191n/a
192n/a# Reserved ranges
193n/a
194n/a# First Last Count Purpose
195n/a# 1 127 127 Reserved for Python standard library
196n/a# 128 191 64 Reserved for Zope
197n/a# 192 239 48 Reserved for 3rd parties
198n/a# 240 255 16 Reserved for private use (will never be assigned)
199n/a# 256 Inf Inf Reserved for future assignment
200n/a
201n/a# Extension codes are assigned by the Python Software Foundation.