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

Python code coverage for Lib/copyreg.py

#countcontent
1n/a"""Helper to provide extensibility for pickle.
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
7n/a__all__ = ["pickle", "constructor",
8n/a "add_extension", "remove_extension", "clear_extension_cache"]
9n/a
10n/adispatch_table = {}
11n/a
12n/adef pickle(ob_type, pickle_function, constructor_ob=None):
13n/a if not callable(pickle_function):
14n/a raise TypeError("reduction functions must be callable")
15n/a dispatch_table[ob_type] = pickle_function
16n/a
17n/a # The constructor_ob function is a vestige of safe for unpickling.
18n/a # There is no reason for the caller to pass it anymore.
19n/a if constructor_ob is not None:
20n/a constructor(constructor_ob)
21n/a
22n/adef constructor(object):
23n/a if not callable(object):
24n/a raise TypeError("constructors must be callable")
25n/a
26n/a# Example: provide pickling support for complex numbers.
27n/a
28n/atry:
29n/a complex
30n/aexcept NameError:
31n/a pass
32n/aelse:
33n/a
34n/a def pickle_complex(c):
35n/a return complex, (c.real, c.imag)
36n/a
37n/a pickle(complex, pickle_complex, complex)
38n/a
39n/a# Support for pickling new-style objects
40n/a
41n/adef _reconstructor(cls, base, state):
42n/a if base is object:
43n/a obj = object.__new__(cls)
44n/a else:
45n/a obj = base.__new__(cls, state)
46n/a if base.__init__ != object.__init__:
47n/a base.__init__(obj, state)
48n/a return obj
49n/a
50n/a_HEAPTYPE = 1<<9
51n/a
52n/a# Python code for object.__reduce_ex__ for protocols 0 and 1
53n/a
54n/adef _reduce_ex(self, proto):
55n/a assert proto < 2
56n/a for base in self.__class__.__mro__:
57n/a if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
58n/a break
59n/a else:
60n/a base = object # not really reachable
61n/a if base is object:
62n/a state = None
63n/a else:
64n/a if base is self.__class__:
65n/a raise TypeError("can't pickle %s objects" % base.__name__)
66n/a state = base(self)
67n/a args = (self.__class__, base, state)
68n/a try:
69n/a getstate = self.__getstate__
70n/a except AttributeError:
71n/a if getattr(self, "__slots__", None):
72n/a raise TypeError("a class that defines __slots__ without "
73n/a "defining __getstate__ cannot be pickled")
74n/a try:
75n/a dict = self.__dict__
76n/a except AttributeError:
77n/a dict = None
78n/a else:
79n/a dict = getstate()
80n/a if dict:
81n/a return _reconstructor, args, dict
82n/a else:
83n/a return _reconstructor, args
84n/a
85n/a# Helper for __reduce_ex__ protocol 2
86n/a
87n/adef __newobj__(cls, *args):
88n/a return cls.__new__(cls, *args)
89n/a
90n/adef __newobj_ex__(cls, args, kwargs):
91n/a """Used by pickle protocol 4, instead of __newobj__ to allow classes with
92n/a keyword-only arguments to be pickled correctly.
93n/a """
94n/a return cls.__new__(cls, *args, **kwargs)
95n/a
96n/adef _slotnames(cls):
97n/a """Return a list of slot names for a given class.
98n/a
99n/a This needs to find slots defined by the class and its bases, so we
100n/a can't simply return the __slots__ attribute. We must walk down
101n/a the Method Resolution Order and concatenate the __slots__ of each
102n/a class found there. (This assumes classes don't modify their
103n/a __slots__ attribute to misrepresent their slots after the class is
104n/a defined.)
105n/a """
106n/a
107n/a # Get the value from a cache in the class if possible
108n/a names = cls.__dict__.get("__slotnames__")
109n/a if names is not None:
110n/a return names
111n/a
112n/a # Not cached -- calculate the value
113n/a names = []
114n/a if not hasattr(cls, "__slots__"):
115n/a # This class has no slots
116n/a pass
117n/a else:
118n/a # Slots found -- gather slot names from all base classes
119n/a for c in cls.__mro__:
120n/a if "__slots__" in c.__dict__:
121n/a slots = c.__dict__['__slots__']
122n/a # if class has a single slot, it can be given as a string
123n/a if isinstance(slots, str):
124n/a slots = (slots,)
125n/a for name in slots:
126n/a # special descriptors
127n/a if name in ("__dict__", "__weakref__"):
128n/a continue
129n/a # mangled names
130n/a elif name.startswith('__') and not name.endswith('__'):
131n/a names.append('_%s%s' % (c.__name__, name))
132n/a else:
133n/a names.append(name)
134n/a
135n/a # Cache the outcome in the class if at all possible
136n/a try:
137n/a cls.__slotnames__ = names
138n/a except:
139n/a pass # But don't die if we can't
140n/a
141n/a return names
142n/a
143n/a# A registry of extension codes. This is an ad-hoc compression
144n/a# mechanism. Whenever a global reference to <module>, <name> is about
145n/a# to be pickled, the (<module>, <name>) tuple is looked up here to see
146n/a# if it is a registered extension code for it. Extension codes are
147n/a# universal, so that the meaning of a pickle does not depend on
148n/a# context. (There are also some codes reserved for local use that
149n/a# don't have this restriction.) Codes are positive ints; 0 is
150n/a# reserved.
151n/a
152n/a_extension_registry = {} # key -> code
153n/a_inverted_registry = {} # code -> key
154n/a_extension_cache = {} # code -> object
155n/a# Don't ever rebind those names: pickling grabs a reference to them when
156n/a# it's initialized, and won't see a rebinding.
157n/a
158n/adef add_extension(module, name, code):
159n/a """Register an extension code."""
160n/a code = int(code)
161n/a if not 1 <= code <= 0x7fffffff:
162n/a raise ValueError("code out of range")
163n/a key = (module, name)
164n/a if (_extension_registry.get(key) == code and
165n/a _inverted_registry.get(code) == key):
166n/a return # Redundant registrations are benign
167n/a if key in _extension_registry:
168n/a raise ValueError("key %s is already registered with code %s" %
169n/a (key, _extension_registry[key]))
170n/a if code in _inverted_registry:
171n/a raise ValueError("code %s is already in use for key %s" %
172n/a (code, _inverted_registry[code]))
173n/a _extension_registry[key] = code
174n/a _inverted_registry[code] = key
175n/a
176n/adef remove_extension(module, name, code):
177n/a """Unregister an extension code. For testing only."""
178n/a key = (module, name)
179n/a if (_extension_registry.get(key) != code or
180n/a _inverted_registry.get(code) != key):
181n/a raise ValueError("key %s is not registered with code %s" %
182n/a (key, code))
183n/a del _extension_registry[key]
184n/a del _inverted_registry[code]
185n/a if code in _extension_cache:
186n/a del _extension_cache[code]
187n/a
188n/adef clear_extension_cache():
189n/a _extension_cache.clear()
190n/a
191n/a# Standard extension code assignments
192n/a
193n/a# Reserved ranges
194n/a
195n/a# First Last Count Purpose
196n/a# 1 127 127 Reserved for Python standard library
197n/a# 128 191 64 Reserved for Zope
198n/a# 192 239 48 Reserved for 3rd parties
199n/a# 240 255 16 Reserved for private use (will never be assigned)
200n/a# 256 Inf Inf Reserved for future assignment
201n/a
202n/a# Extension codes are assigned by the Python Software Foundation.