1"""Pickler class to extend the standard pickle.Pickler functionality
2
3The main objective is to make it natural to perform distributed computing on
4clusters (such as PySpark, Dask, Ray...) with interactively defined code
5(functions, classes, ...) written in notebooks or console.
6
7In particular this pickler adds the following features:
8- serialize interactively-defined or locally-defined functions, classes,
9 enums, typevars, lambdas and nested functions to compiled byte code;
10- deal with some other non-serializable objects in an ad-hoc manner where
11 applicable.
12
13This pickler is therefore meant to be used for the communication between short
14lived Python processes running the same version of Python and libraries. In
15particular, it is not meant to be used for long term storage of Python objects.
16
17It does not include an unpickler, as standard Python unpickling suffices.
18
19This module was extracted from the `cloud` package, developed by `PiCloud, Inc.
20<https://web.archive.org/web/20140626004012/http://www.picloud.com/>`_.
21
22Copyright (c) 2012-now, CloudPickle developers and contributors.
23Copyright (c) 2012, Regents of the University of California.
24Copyright (c) 2009 `PiCloud, Inc. <https://web.archive.org/web/20140626004012/http://www.picloud.com/>`_.
25All rights reserved.
26
27Redistribution and use in source and binary forms, with or without
28modification, are permitted provided that the following conditions
29are met:
30 * Redistributions of source code must retain the above copyright
31 notice, this list of conditions and the following disclaimer.
32 * Redistributions in binary form must reproduce the above copyright
33 notice, this list of conditions and the following disclaimer in the
34 documentation and/or other materials provided with the distribution.
35 * Neither the name of the University of California, Berkeley nor the
36 names of its contributors may be used to endorse or promote
37 products derived from this software without specific prior written
38 permission.
39
40THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
41"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
42LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
43A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
44HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
46TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
47PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
48LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
49NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
50SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51"""
52
53import _collections_abc
54from collections import ChainMap, OrderedDict
55import abc
56import builtins
57import copyreg
58import dataclasses
59import dis
60from enum import Enum
61import io
62import itertools
63import logging
64import opcode
65import pickle
66from pickle import _getattribute as _pickle_getattribute
67import platform
68import struct
69import sys
70import threading
71import types
72import typing
73import uuid
74import warnings
75import weakref
76
77# The following import is required to be imported in the cloudpickle
78# namespace to be able to load pickle files generated with older versions of
79# cloudpickle. See: tests/test_backward_compat.py
80from types import CellType # noqa: F401
81
82# cloudpickle is meant for inter process communication: we expect all
83# communicating processes to run the same Python version hence we favor
84# communication speed over compatibility:
85DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL
86
87# Names of modules whose resources should be treated as dynamic.
88_PICKLE_BY_VALUE_MODULES = set()
89
90# Track the provenance of reconstructed dynamic classes to make it possible to
91# reconstruct instances from the matching singleton class definition when
92# appropriate and preserve the usual "isinstance" semantics of Python objects.
93_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary()
94_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary()
95_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock()
96
97PYPY = platform.python_implementation() == "PyPy"
98
99builtin_code_type = None
100if PYPY:
101 # builtin-code objects only exist in pypy
102 builtin_code_type = type(float.__new__.__code__)
103
104_extract_code_globals_cache = weakref.WeakKeyDictionary()
105
106
107def _get_or_create_tracker_id(class_def):
108 with _DYNAMIC_CLASS_TRACKER_LOCK:
109 class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def)
110 if class_tracker_id is None:
111 class_tracker_id = uuid.uuid4().hex
112 _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
113 _DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def
114 return class_tracker_id
115
116
117def _lookup_class_or_track(class_tracker_id, class_def):
118 if class_tracker_id is not None:
119 with _DYNAMIC_CLASS_TRACKER_LOCK:
120 class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(
121 class_tracker_id, class_def
122 )
123 _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
124 return class_def
125
126
127def register_pickle_by_value(module):
128 """Register a module to make its functions and classes picklable by value.
129
130 By default, functions and classes that are attributes of an importable
131 module are to be pickled by reference, that is relying on re-importing
132 the attribute from the module at load time.
133
134 If `register_pickle_by_value(module)` is called, all its functions and
135 classes are subsequently to be pickled by value, meaning that they can
136 be loaded in Python processes where the module is not importable.
137
138 This is especially useful when developing a module in a distributed
139 execution environment: restarting the client Python process with the new
140 source code is enough: there is no need to re-install the new version
141 of the module on all the worker nodes nor to restart the workers.
142
143 Note: this feature is considered experimental. See the cloudpickle
144 README.md file for more details and limitations.
145 """
146 if not isinstance(module, types.ModuleType):
147 raise ValueError(f"Input should be a module object, got {str(module)} instead")
148 # In the future, cloudpickle may need a way to access any module registered
149 # for pickling by value in order to introspect relative imports inside
150 # functions pickled by value. (see
151 # https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633).
152 # This access can be ensured by checking that module is present in
153 # sys.modules at registering time and assuming that it will still be in
154 # there when accessed during pickling. Another alternative would be to
155 # store a weakref to the module. Even though cloudpickle does not implement
156 # this introspection yet, in order to avoid a possible breaking change
157 # later, we still enforce the presence of module inside sys.modules.
158 if module.__name__ not in sys.modules:
159 raise ValueError(
160 f"{module} was not imported correctly, have you used an "
161 "`import` statement to access it?"
162 )
163 _PICKLE_BY_VALUE_MODULES.add(module.__name__)
164
165
166def unregister_pickle_by_value(module):
167 """Unregister that the input module should be pickled by value."""
168 if not isinstance(module, types.ModuleType):
169 raise ValueError(f"Input should be a module object, got {str(module)} instead")
170 if module.__name__ not in _PICKLE_BY_VALUE_MODULES:
171 raise ValueError(f"{module} is not registered for pickle by value")
172 else:
173 _PICKLE_BY_VALUE_MODULES.remove(module.__name__)
174
175
176def list_registry_pickle_by_value():
177 return _PICKLE_BY_VALUE_MODULES.copy()
178
179
180def _is_registered_pickle_by_value(module):
181 module_name = module.__name__
182 if module_name in _PICKLE_BY_VALUE_MODULES:
183 return True
184 while True:
185 parent_name = module_name.rsplit(".", 1)[0]
186 if parent_name == module_name:
187 break
188 if parent_name in _PICKLE_BY_VALUE_MODULES:
189 return True
190 module_name = parent_name
191 return False
192
193
194if sys.version_info >= (3, 14):
195
196 def _getattribute(obj, name):
197 return _pickle_getattribute(obj, name.split("."))
198
199else:
200
201 def _getattribute(obj, name):
202 return _pickle_getattribute(obj, name)[0]
203
204
205def _whichmodule(obj, name):
206 """Find the module an object belongs to.
207
208 This function differs from ``pickle.whichmodule`` in two ways:
209 - it does not mangle the cases where obj's module is __main__ and obj was
210 not found in any module.
211 - Errors arising during module introspection are ignored, as those errors
212 are considered unwanted side effects.
213 """
214 module_name = getattr(obj, "__module__", None)
215
216 if module_name is not None:
217 return module_name
218 # Protect the iteration by using a copy of sys.modules against dynamic
219 # modules that trigger imports of other modules upon calls to getattr or
220 # other threads importing at the same time.
221 for module_name, module in sys.modules.copy().items():
222 # Some modules such as coverage can inject non-module objects inside
223 # sys.modules
224 if (
225 module_name == "__main__"
226 or module_name == "__mp_main__"
227 or module is None
228 or not isinstance(module, types.ModuleType)
229 ):
230 continue
231 try:
232 if _getattribute(module, name) is obj:
233 return module_name
234 except Exception:
235 pass
236 return None
237
238
239def _should_pickle_by_reference(obj, name=None):
240 """Test whether an function or a class should be pickled by reference
241
242 Pickling by reference means by that the object (typically a function or a
243 class) is an attribute of a module that is assumed to be importable in the
244 target Python environment. Loading will therefore rely on importing the
245 module and then calling `getattr` on it to access the function or class.
246
247 Pickling by reference is the only option to pickle functions and classes
248 in the standard library. In cloudpickle the alternative option is to
249 pickle by value (for instance for interactively or locally defined
250 functions and classes or for attributes of modules that have been
251 explicitly registered to be pickled by value.
252 """
253 if isinstance(obj, types.FunctionType) or issubclass(type(obj), type):
254 module_and_name = _lookup_module_and_qualname(obj, name=name)
255 if module_and_name is None:
256 return False
257 module, name = module_and_name
258 return not _is_registered_pickle_by_value(module)
259
260 elif isinstance(obj, types.ModuleType):
261 # We assume that sys.modules is primarily used as a cache mechanism for
262 # the Python import machinery. Checking if a module has been added in
263 # is sys.modules therefore a cheap and simple heuristic to tell us
264 # whether we can assume that a given module could be imported by name
265 # in another Python process.
266 if _is_registered_pickle_by_value(obj):
267 return False
268 return obj.__name__ in sys.modules
269 else:
270 raise TypeError(
271 "cannot check importability of {} instances".format(type(obj).__name__)
272 )
273
274
275def _lookup_module_and_qualname(obj, name=None):
276 if name is None:
277 name = getattr(obj, "__qualname__", None)
278 if name is None: # pragma: no cover
279 # This used to be needed for Python 2.7 support but is probably not
280 # needed anymore. However we keep the __name__ introspection in case
281 # users of cloudpickle rely on this old behavior for unknown reasons.
282 name = getattr(obj, "__name__", None)
283
284 module_name = _whichmodule(obj, name)
285
286 if module_name is None:
287 # In this case, obj.__module__ is None AND obj was not found in any
288 # imported module. obj is thus treated as dynamic.
289 return None
290
291 if module_name == "__main__":
292 return None
293
294 # Note: if module_name is in sys.modules, the corresponding module is
295 # assumed importable at unpickling time. See #357
296 module = sys.modules.get(module_name, None)
297 if module is None:
298 # The main reason why obj's module would not be imported is that this
299 # module has been dynamically created, using for example
300 # types.ModuleType. The other possibility is that module was removed
301 # from sys.modules after obj was created/imported. But this case is not
302 # supported, as the standard pickle does not support it either.
303 return None
304
305 try:
306 obj2 = _getattribute(module, name)
307 except AttributeError:
308 # obj was not found inside the module it points to
309 return None
310 if obj2 is not obj:
311 return None
312 return module, name
313
314
315def _extract_code_globals(co):
316 """Find all globals names read or written to by codeblock co."""
317 out_names = _extract_code_globals_cache.get(co)
318 if out_names is None:
319 # We use a dict with None values instead of a set to get a
320 # deterministic order and avoid introducing non-deterministic pickle
321 # bytes as a results.
322 out_names = {name: None for name in _walk_global_ops(co)}
323
324 # Declaring a function inside another one using the "def ..." syntax
325 # generates a constant code object corresponding to the one of the
326 # nested function's As the nested function may itself need global
327 # variables, we need to introspect its code, extract its globals, (look
328 # for code object in it's co_consts attribute..) and add the result to
329 # code_globals
330 if co.co_consts:
331 for const in co.co_consts:
332 if isinstance(const, types.CodeType):
333 out_names.update(_extract_code_globals(const))
334
335 _extract_code_globals_cache[co] = out_names
336
337 return out_names
338
339
340def _find_imported_submodules(code, top_level_dependencies):
341 """Find currently imported submodules used by a function.
342
343 Submodules used by a function need to be detected and referenced for the
344 function to work correctly at depickling time. Because submodules can be
345 referenced as attribute of their parent package (``package.submodule``), we
346 need a special introspection technique that does not rely on GLOBAL-related
347 opcodes to find references of them in a code object.
348
349 Example:
350 ```
351 import concurrent.futures
352 import cloudpickle
353 def func():
354 x = concurrent.futures.ThreadPoolExecutor
355 if __name__ == '__main__':
356 cloudpickle.dumps(func)
357 ```
358 The globals extracted by cloudpickle in the function's state include the
359 concurrent package, but not its submodule (here, concurrent.futures), which
360 is the module used by func. Find_imported_submodules will detect the usage
361 of concurrent.futures. Saving this module alongside with func will ensure
362 that calling func once depickled does not fail due to concurrent.futures
363 not being imported
364 """
365
366 subimports = []
367 # check if any known dependency is an imported package
368 for x in top_level_dependencies:
369 if (
370 isinstance(x, types.ModuleType)
371 and hasattr(x, "__package__")
372 and x.__package__
373 ):
374 # check if the package has any currently loaded sub-imports
375 prefix = x.__name__ + "."
376 # A concurrent thread could mutate sys.modules,
377 # make sure we iterate over a copy to avoid exceptions
378 for name in list(sys.modules):
379 # Older versions of pytest will add a "None" module to
380 # sys.modules.
381 if name is not None and name.startswith(prefix):
382 # check whether the function can address the sub-module
383 tokens = set(name[len(prefix) :].split("."))
384 if not tokens - set(code.co_names):
385 subimports.append(sys.modules[name])
386 return subimports
387
388
389# relevant opcodes
390STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"]
391_glbl_ops = [STORE_GLOBAL]
392if sys.version_info < (3, 16):
393 DELETE_GLOBAL = opcode.opmap["DELETE_GLOBAL"]
394 _glbl_ops.append(DELETE_GLOBAL)
395LOAD_GLOBAL = opcode.opmap["LOAD_GLOBAL"]
396_glbl_ops.append(LOAD_GLOBAL)
397GLOBAL_OPS = tuple(_glbl_ops)
398del _glbl_ops
399HAVE_ARGUMENT = dis.HAVE_ARGUMENT
400EXTENDED_ARG = dis.EXTENDED_ARG
401
402
403_BUILTIN_TYPE_NAMES = {}
404for k, v in types.__dict__.items():
405 if type(v) is type:
406 _BUILTIN_TYPE_NAMES[v] = k
407
408
409def _builtin_type(name):
410 if name == "ClassType": # pragma: no cover
411 # Backward compat to load pickle files generated with cloudpickle
412 # < 1.3 even if loading pickle files from older versions is not
413 # officially supported.
414 return type
415 return getattr(types, name)
416
417
418def _walk_global_ops(code):
419 """Yield referenced name for global-referencing instructions in code."""
420 for instr in dis.get_instructions(code):
421 op = instr.opcode
422 if op in GLOBAL_OPS:
423 yield instr.argval
424
425
426def _extract_class_dict(cls):
427 """Retrieve a copy of the dict of a class without the inherited method."""
428 # Hack to circumvent non-predictable memoization caused by string interning.
429 # See the inline comment in _class_setstate for details.
430 clsdict = {"".join(k): cls.__dict__[k] for k in sorted(cls.__dict__)}
431
432 if len(cls.__bases__) == 1:
433 inherited_dict = cls.__bases__[0].__dict__
434 else:
435 inherited_dict = {}
436 for base in reversed(cls.__bases__):
437 inherited_dict.update(base.__dict__)
438 to_remove = []
439 for name, value in clsdict.items():
440 try:
441 base_value = inherited_dict[name]
442 if value is base_value:
443 to_remove.append(name)
444 except KeyError:
445 pass
446 for name in to_remove:
447 clsdict.pop(name)
448 return clsdict
449
450
451def is_tornado_coroutine(func):
452 """Return whether `func` is a Tornado coroutine function.
453
454 Running coroutines are not supported.
455 """
456 warnings.warn(
457 "is_tornado_coroutine is deprecated in cloudpickle 3.0 and will be "
458 "removed in cloudpickle 4.0. Use tornado.gen.is_coroutine_function "
459 "directly instead.",
460 category=DeprecationWarning,
461 )
462 if "tornado.gen" not in sys.modules:
463 return False
464 gen = sys.modules["tornado.gen"]
465 if not hasattr(gen, "is_coroutine_function"):
466 # Tornado version is too old
467 return False
468 return gen.is_coroutine_function(func)
469
470
471def subimport(name):
472 # We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is
473 # the name of a submodule, __import__ will return the top-level root module
474 # of this submodule. For instance, __import__('os.path') returns the `os`
475 # module.
476 __import__(name)
477 return sys.modules[name]
478
479
480def dynamic_subimport(name, vars):
481 mod = types.ModuleType(name)
482 mod.__dict__.update(vars)
483 mod.__dict__["__builtins__"] = builtins.__dict__
484 return mod
485
486
487def _get_cell_contents(cell):
488 try:
489 return cell.cell_contents
490 except ValueError:
491 # Handle empty cells explicitly with a sentinel value.
492 return _empty_cell_value
493
494
495def instance(cls):
496 """Create a new instance of a class.
497
498 Parameters
499 ----------
500 cls : type
501 The class to create an instance of.
502
503 Returns
504 -------
505 instance : cls
506 A new instance of ``cls``.
507 """
508 return cls()
509
510
511@instance
512class _empty_cell_value:
513 """Sentinel for empty closures."""
514
515 @classmethod
516 def __reduce__(cls):
517 return cls.__name__
518
519
520def _make_function(code, globals, name, argdefs, closure):
521 # Setting __builtins__ in globals is needed for nogil CPython.
522 globals["__builtins__"] = __builtins__
523 return types.FunctionType(code, globals, name, argdefs, closure)
524
525
526def _make_empty_cell():
527 if False:
528 # trick the compiler into creating an empty cell in our lambda
529 cell = None
530 raise AssertionError("this route should not be executed")
531
532 return (lambda: cell).__closure__[0]
533
534
535def _make_cell(value=_empty_cell_value):
536 cell = _make_empty_cell()
537 if value is not _empty_cell_value:
538 cell.cell_contents = value
539 return cell
540
541
542def _make_skeleton_class(
543 type_constructor, name, bases, type_kwargs, class_tracker_id, extra
544):
545 """Build dynamic class with an empty __dict__ to be filled once memoized
546
547 If class_tracker_id is not None, try to lookup an existing class definition
548 matching that id. If none is found, track a newly reconstructed class
549 definition under that id so that other instances stemming from the same
550 class id will also reuse this class definition.
551
552 The "extra" variable is meant to be a dict (or None) that can be used for
553 forward compatibility shall the need arise.
554 """
555 # We need to intern the keys of the type_kwargs dict to avoid having
556 # different pickles for the same dynamic class depending on whether it was
557 # dynamically created or reconstructed from a pickled stream.
558 type_kwargs = {sys.intern(k): v for k, v in type_kwargs.items()}
559
560 skeleton_class = types.new_class(
561 name, bases, {"metaclass": type_constructor}, lambda ns: ns.update(type_kwargs)
562 )
563
564 return _lookup_class_or_track(class_tracker_id, skeleton_class)
565
566
567def _make_skeleton_enum(
568 bases, name, qualname, members, module, class_tracker_id, extra
569):
570 """Build dynamic enum with an empty __dict__ to be filled once memoized
571
572 The creation of the enum class is inspired by the code of
573 EnumMeta._create_.
574
575 If class_tracker_id is not None, try to lookup an existing enum definition
576 matching that id. If none is found, track a newly reconstructed enum
577 definition under that id so that other instances stemming from the same
578 class id will also reuse this enum definition.
579
580 The "extra" variable is meant to be a dict (or None) that can be used for
581 forward compatibility shall the need arise.
582 """
583 # enums always inherit from their base Enum class at the last position in
584 # the list of base classes:
585 enum_base = bases[-1]
586 metacls = enum_base.__class__
587 classdict = metacls.__prepare__(name, bases)
588
589 for member_name, member_value in members.items():
590 classdict[member_name] = member_value
591 enum_class = metacls.__new__(metacls, name, bases, classdict)
592 enum_class.__module__ = module
593 enum_class.__qualname__ = qualname
594
595 return _lookup_class_or_track(class_tracker_id, enum_class)
596
597
598def _make_typevar(name, bound, constraints, covariant, contravariant, class_tracker_id):
599 tv = typing.TypeVar(
600 name,
601 *constraints,
602 bound=bound,
603 covariant=covariant,
604 contravariant=contravariant,
605 )
606 return _lookup_class_or_track(class_tracker_id, tv)
607
608
609def _decompose_typevar(obj):
610 return (
611 obj.__name__,
612 obj.__bound__,
613 obj.__constraints__,
614 obj.__covariant__,
615 obj.__contravariant__,
616 _get_or_create_tracker_id(obj),
617 )
618
619
620def _typevar_reduce(obj):
621 # TypeVar instances require the module information hence why we
622 # are not using the _should_pickle_by_reference directly
623 module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__)
624
625 if module_and_name is None:
626 return (_make_typevar, _decompose_typevar(obj))
627 elif _is_registered_pickle_by_value(module_and_name[0]):
628 return (_make_typevar, _decompose_typevar(obj))
629
630 return (getattr, module_and_name)
631
632
633def _get_bases(typ):
634 if "__orig_bases__" in getattr(typ, "__dict__", {}):
635 # For generic types (see PEP 560)
636 # Note that simply checking `hasattr(typ, '__orig_bases__')` is not
637 # correct. Subclasses of a fully-parameterized generic class does not
638 # have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')`
639 # will return True because it's defined in the base class.
640 bases_attr = "__orig_bases__"
641 else:
642 # For regular class objects
643 bases_attr = "__bases__"
644 return getattr(typ, bases_attr)
645
646
647def _make_dict_keys(obj, is_ordered=False):
648 if is_ordered:
649 return OrderedDict.fromkeys(obj).keys()
650 else:
651 return dict.fromkeys(obj).keys()
652
653
654def _make_dict_values(obj, is_ordered=False):
655 if is_ordered:
656 return OrderedDict((i, _) for i, _ in enumerate(obj)).values()
657 else:
658 return {i: _ for i, _ in enumerate(obj)}.values()
659
660
661def _make_dict_items(obj, is_ordered=False):
662 if is_ordered:
663 return OrderedDict(obj).items()
664 else:
665 return obj.items()
666
667
668# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS
669# -------------------------------------------------
670
671
672def _class_getnewargs(obj):
673 type_kwargs = {}
674 if "__module__" in obj.__dict__:
675 type_kwargs["__module__"] = obj.__module__
676
677 __dict__ = obj.__dict__.get("__dict__", None)
678 if isinstance(__dict__, property):
679 type_kwargs["__dict__"] = __dict__
680
681 return (
682 type(obj),
683 obj.__name__,
684 _get_bases(obj),
685 type_kwargs,
686 _get_or_create_tracker_id(obj),
687 None,
688 )
689
690
691def _enum_getnewargs(obj):
692 members = {e.name: e.value for e in obj}
693 return (
694 obj.__bases__,
695 obj.__name__,
696 obj.__qualname__,
697 members,
698 obj.__module__,
699 _get_or_create_tracker_id(obj),
700 None,
701 )
702
703
704# COLLECTION OF OBJECTS RECONSTRUCTORS
705# ------------------------------------
706def _file_reconstructor(retval):
707 return retval
708
709
710# COLLECTION OF OBJECTS STATE GETTERS
711# -----------------------------------
712
713
714def _function_getstate(func):
715 # - Put func's dynamic attributes (stored in func.__dict__) in state. These
716 # attributes will be restored at unpickling time using
717 # f.__dict__.update(state)
718 # - Put func's members into slotstate. Such attributes will be restored at
719 # unpickling time by iterating over slotstate and calling setattr(func,
720 # slotname, slotvalue)
721 slotstate = {
722 # Hack to circumvent non-predictable memoization caused by string interning.
723 # See the inline comment in _class_setstate for details.
724 "__name__": "".join(func.__name__),
725 "__qualname__": "".join(func.__qualname__),
726 "__annotations__": func.__annotations__,
727 "__kwdefaults__": func.__kwdefaults__,
728 "__defaults__": func.__defaults__,
729 "__module__": func.__module__,
730 "__doc__": func.__doc__,
731 "__closure__": func.__closure__,
732 }
733
734 f_globals_ref = _extract_code_globals(func.__code__)
735 f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in func.__globals__}
736
737 if func.__closure__ is not None:
738 closure_values = list(map(_get_cell_contents, func.__closure__))
739 else:
740 closure_values = ()
741
742 # Extract currently-imported submodules used by func. Storing these modules
743 # in a smoke _cloudpickle_subimports attribute of the object's state will
744 # trigger the side effect of importing these modules at unpickling time
745 # (which is necessary for func to work correctly once depickled)
746 slotstate["_cloudpickle_submodules"] = _find_imported_submodules(
747 func.__code__, itertools.chain(f_globals.values(), closure_values)
748 )
749 slotstate["__globals__"] = f_globals
750
751 # Hack to circumvent non-predictable memoization caused by string interning.
752 # See the inline comment in _class_setstate for details.
753 state = {"".join(k): v for k, v in func.__dict__.items()}
754 return state, slotstate
755
756
757def _class_getstate(obj):
758 clsdict = _extract_class_dict(obj)
759 clsdict.pop("__weakref__", None)
760
761 if issubclass(type(obj), abc.ABCMeta):
762 # If obj is an instance of an ABCMeta subclass, don't pickle the
763 # cache/negative caches populated during isinstance/issubclass
764 # checks, but pickle the list of registered subclasses of obj.
765 clsdict.pop("_abc_cache", None)
766 clsdict.pop("_abc_negative_cache", None)
767 clsdict.pop("_abc_negative_cache_version", None)
768 registry = clsdict.pop("_abc_registry", None)
769 if registry is None:
770 # The abc caches and registered subclasses of a
771 # class are bundled into the single _abc_impl attribute
772 clsdict.pop("_abc_impl", None)
773 (registry, _, _, _) = abc._get_dump(obj)
774
775 clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry]
776 else:
777 # In the above if clause, registry is a set of weakrefs -- in
778 # this case, registry is a WeakSet
779 clsdict["_abc_impl"] = [type_ for type_ in registry]
780
781 if "__slots__" in clsdict:
782 # pickle string length optimization: member descriptors of obj are
783 # created automatically from obj's __slots__ attribute, no need to
784 # save them in obj's state
785 if isinstance(obj.__slots__, str):
786 clsdict.pop(obj.__slots__)
787 else:
788 for k in obj.__slots__:
789 clsdict.pop(k, None)
790
791 clsdict.pop("__dict__", None) # unpicklable property object
792
793 if sys.version_info >= (3, 14):
794 # PEP-649/749: __annotate_func__ contains a closure that references the class
795 # dict. We need to exclude it from pickling. Python will recreate it when
796 # __annotations__ is accessed at unpickling time.
797 clsdict.pop("__annotate_func__", None)
798
799 return (clsdict, {})
800
801
802def _enum_getstate(obj):
803 clsdict, slotstate = _class_getstate(obj)
804
805 members = {e.name: e.value for e in obj}
806 # Cleanup the clsdict that will be passed to _make_skeleton_enum:
807 # Those attributes are already handled by the metaclass.
808 for attrname in [
809 "_generate_next_value_",
810 "_member_names_",
811 "_member_map_",
812 "_member_type_",
813 "_value2member_map_",
814 ]:
815 clsdict.pop(attrname, None)
816 for member in members:
817 clsdict.pop(member)
818 # Special handling of Enum subclasses
819 return clsdict, slotstate
820
821
822# COLLECTIONS OF OBJECTS REDUCERS
823# -------------------------------
824# A reducer is a function taking a single argument (obj), and that returns a
825# tuple with all the necessary data to re-construct obj. Apart from a few
826# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to
827# correctly pickle an object.
828# While many built-in objects (Exceptions objects, instances of the "object"
829# class, etc), are shipped with their own built-in reducer (invoked using
830# obj.__reduce__), some do not. The following methods were created to "fill
831# these holes".
832
833
834def _code_reduce(obj):
835 """code object reducer."""
836 # If you are not sure about the order of arguments, take a look at help
837 # of the specific type from types, for example:
838 # >>> from types import CodeType
839 # >>> help(CodeType)
840
841 # Hack to circumvent non-predictable memoization caused by string interning.
842 # See the inline comment in _class_setstate for details.
843 co_name = "".join(obj.co_name)
844
845 # co_filename is not used in the constructor of code objects, so we can
846 # safely set it to indicate that this is dynamic code. This also makes
847 # the payload deterministic, independent of where the function is defined
848 # which is especially useful when defining classes in jupyter/ipython
849 # cells which do not have a deterministic filename.
850 co_filename = "".join("<dynamic-code>")
851
852 # Create shallow copies of these tuple to make cloudpickle payload deterministic.
853 # When creating a code object during load, copies of these four tuples are
854 # created, while in the main process, these tuples can be shared.
855 # By always creating copies, we make sure the resulting payload is deterministic.
856 co_names = tuple(name for name in obj.co_names)
857 co_varnames = tuple(name for name in obj.co_varnames)
858 co_freevars = tuple(name for name in obj.co_freevars)
859 co_cellvars = tuple(name for name in obj.co_cellvars)
860 if hasattr(obj, "co_exceptiontable"):
861 # Python 3.11 and later: there are some new attributes
862 # related to the enhanced exceptions.
863 args = (
864 obj.co_argcount,
865 obj.co_posonlyargcount,
866 obj.co_kwonlyargcount,
867 obj.co_nlocals,
868 obj.co_stacksize,
869 obj.co_flags,
870 obj.co_code,
871 obj.co_consts,
872 co_names,
873 co_varnames,
874 co_filename,
875 co_name,
876 obj.co_qualname,
877 obj.co_firstlineno,
878 obj.co_linetable,
879 obj.co_exceptiontable,
880 co_freevars,
881 co_cellvars,
882 )
883 elif hasattr(obj, "co_linetable"):
884 # Python 3.10 and later: obj.co_lnotab is deprecated and constructor
885 # expects obj.co_linetable instead.
886 args = (
887 obj.co_argcount,
888 obj.co_posonlyargcount,
889 obj.co_kwonlyargcount,
890 obj.co_nlocals,
891 obj.co_stacksize,
892 obj.co_flags,
893 obj.co_code,
894 obj.co_consts,
895 co_names,
896 co_varnames,
897 co_filename,
898 co_name,
899 obj.co_firstlineno,
900 obj.co_linetable,
901 co_freevars,
902 co_cellvars,
903 )
904 elif hasattr(obj, "co_nmeta"): # pragma: no cover
905 # "nogil" Python: modified attributes from 3.9
906 args = (
907 obj.co_argcount,
908 obj.co_posonlyargcount,
909 obj.co_kwonlyargcount,
910 obj.co_nlocals,
911 obj.co_framesize,
912 obj.co_ndefaultargs,
913 obj.co_nmeta,
914 obj.co_flags,
915 obj.co_code,
916 obj.co_consts,
917 co_varnames,
918 co_filename,
919 co_name,
920 obj.co_firstlineno,
921 obj.co_lnotab,
922 obj.co_exc_handlers,
923 obj.co_jump_table,
924 co_freevars,
925 co_cellvars,
926 obj.co_free2reg,
927 obj.co_cell2reg,
928 )
929 else:
930 # Backward compat for 3.8 and 3.9
931 args = (
932 obj.co_argcount,
933 obj.co_posonlyargcount,
934 obj.co_kwonlyargcount,
935 obj.co_nlocals,
936 obj.co_stacksize,
937 obj.co_flags,
938 obj.co_code,
939 obj.co_consts,
940 co_names,
941 co_varnames,
942 co_filename,
943 co_name,
944 obj.co_firstlineno,
945 obj.co_lnotab,
946 co_freevars,
947 co_cellvars,
948 )
949 return types.CodeType, args
950
951
952def _cell_reduce(obj):
953 """Cell (containing values of a function's free variables) reducer."""
954 try:
955 obj.cell_contents
956 except ValueError: # cell is empty
957 return _make_empty_cell, ()
958 else:
959 return _make_cell, (obj.cell_contents,)
960
961
962def _classmethod_reduce(obj):
963 orig_func = obj.__func__
964 return type(obj), (orig_func,)
965
966
967def _file_reduce(obj):
968 """Save a file."""
969 import io
970
971 if not hasattr(obj, "name") or not hasattr(obj, "mode"):
972 raise pickle.PicklingError(
973 "Cannot pickle files that do not map to an actual file"
974 )
975 if obj is sys.stdout:
976 return getattr, (sys, "stdout")
977 if obj is sys.stderr:
978 return getattr, (sys, "stderr")
979 if obj is sys.stdin:
980 raise pickle.PicklingError("Cannot pickle standard input")
981 if obj.closed:
982 raise pickle.PicklingError("Cannot pickle closed files")
983 if hasattr(obj, "isatty") and obj.isatty():
984 raise pickle.PicklingError("Cannot pickle files that map to tty objects")
985 if "r" not in obj.mode and "+" not in obj.mode:
986 raise pickle.PicklingError(
987 "Cannot pickle files that are not opened for reading: %s" % obj.mode
988 )
989
990 name = obj.name
991
992 retval = io.StringIO()
993
994 try:
995 # Read the whole file
996 curloc = obj.tell()
997 obj.seek(0)
998 contents = obj.read()
999 obj.seek(curloc)
1000 except OSError as e:
1001 raise pickle.PicklingError(
1002 "Cannot pickle file %s as it cannot be read" % name
1003 ) from e
1004 retval.write(contents)
1005 retval.seek(curloc)
1006
1007 retval.name = name
1008 return _file_reconstructor, (retval,)
1009
1010
1011def _getset_descriptor_reduce(obj):
1012 return getattr, (obj.__objclass__, obj.__name__)
1013
1014
1015def _mappingproxy_reduce(obj):
1016 return types.MappingProxyType, (dict(obj),)
1017
1018
1019def _memoryview_reduce(obj):
1020 return bytes, (obj.tobytes(),)
1021
1022
1023def _module_reduce(obj):
1024 if _should_pickle_by_reference(obj):
1025 return subimport, (obj.__name__,)
1026 else:
1027 # Some external libraries can populate the "__builtins__" entry of a
1028 # module's `__dict__` with unpicklable objects (see #316). For that
1029 # reason, we do not attempt to pickle the "__builtins__" entry, and
1030 # restore a default value for it at unpickling time.
1031 state = obj.__dict__.copy()
1032 state.pop("__builtins__", None)
1033 return dynamic_subimport, (obj.__name__, state)
1034
1035
1036def _method_reduce(obj):
1037 return (types.MethodType, (obj.__func__, obj.__self__))
1038
1039
1040def _logger_reduce(obj):
1041 return logging.getLogger, (obj.name,)
1042
1043
1044def _root_logger_reduce(obj):
1045 return logging.getLogger, ()
1046
1047
1048def _property_reduce(obj):
1049 return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__)
1050
1051
1052def _weakset_reduce(obj):
1053 return weakref.WeakSet, (list(obj),)
1054
1055
1056def _dynamic_class_reduce(obj):
1057 """Save a class that can't be referenced as a module attribute.
1058
1059 This method is used to serialize classes that are defined inside
1060 functions, or that otherwise can't be serialized as attribute lookups
1061 from importable modules.
1062 """
1063 if Enum is not None and issubclass(obj, Enum):
1064 return (
1065 _make_skeleton_enum,
1066 _enum_getnewargs(obj),
1067 _enum_getstate(obj),
1068 None,
1069 None,
1070 _class_setstate,
1071 )
1072 else:
1073 return (
1074 _make_skeleton_class,
1075 _class_getnewargs(obj),
1076 _class_getstate(obj),
1077 None,
1078 None,
1079 _class_setstate,
1080 )
1081
1082
1083def _class_reduce(obj):
1084 """Select the reducer depending on the dynamic nature of the class obj."""
1085 if obj is type(None): # noqa
1086 return type, (None,)
1087 elif obj is type(Ellipsis):
1088 return type, (Ellipsis,)
1089 elif obj is type(NotImplemented):
1090 return type, (NotImplemented,)
1091 elif obj in _BUILTIN_TYPE_NAMES:
1092 return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],)
1093 elif not _should_pickle_by_reference(obj):
1094 return _dynamic_class_reduce(obj)
1095 return NotImplemented
1096
1097
1098def _dict_keys_reduce(obj):
1099 # Safer not to ship the full dict as sending the rest might
1100 # be unintended and could potentially cause leaking of
1101 # sensitive information
1102 return _make_dict_keys, (list(obj),)
1103
1104
1105def _dict_values_reduce(obj):
1106 # Safer not to ship the full dict as sending the rest might
1107 # be unintended and could potentially cause leaking of
1108 # sensitive information
1109 return _make_dict_values, (list(obj),)
1110
1111
1112def _dict_items_reduce(obj):
1113 return _make_dict_items, (dict(obj),)
1114
1115
1116def _odict_keys_reduce(obj):
1117 # Safer not to ship the full dict as sending the rest might
1118 # be unintended and could potentially cause leaking of
1119 # sensitive information
1120 return _make_dict_keys, (list(obj), True)
1121
1122
1123def _odict_values_reduce(obj):
1124 # Safer not to ship the full dict as sending the rest might
1125 # be unintended and could potentially cause leaking of
1126 # sensitive information
1127 return _make_dict_values, (list(obj), True)
1128
1129
1130def _odict_items_reduce(obj):
1131 return _make_dict_items, (dict(obj), True)
1132
1133
1134def _dataclass_field_base_reduce(obj):
1135 return _get_dataclass_field_type_sentinel, (obj.name,)
1136
1137
1138# COLLECTIONS OF OBJECTS STATE SETTERS
1139# ------------------------------------
1140# state setters are called at unpickling time, once the object is created and
1141# it has to be updated to how it was at unpickling time.
1142
1143
1144def _function_setstate(obj, state):
1145 """Update the state of a dynamic function.
1146
1147 As __closure__ and __globals__ are readonly attributes of a function, we
1148 cannot rely on the native setstate routine of pickle.load_build, that calls
1149 setattr on items of the slotstate. Instead, we have to modify them inplace.
1150 """
1151 state, slotstate = state
1152 obj.__dict__.update(state)
1153
1154 obj_globals = slotstate.pop("__globals__")
1155 obj_closure = slotstate.pop("__closure__")
1156 # _cloudpickle_subimports is a set of submodules that must be loaded for
1157 # the pickled function to work correctly at unpickling time. Now that these
1158 # submodules are depickled (hence imported), they can be removed from the
1159 # object's state (the object state only served as a reference holder to
1160 # these submodules)
1161 slotstate.pop("_cloudpickle_submodules")
1162
1163 obj.__globals__.update(obj_globals)
1164 obj.__globals__["__builtins__"] = __builtins__
1165
1166 if obj_closure is not None:
1167 for i, cell in enumerate(obj_closure):
1168 try:
1169 value = cell.cell_contents
1170 except ValueError: # cell is empty
1171 continue
1172 obj.__closure__[i].cell_contents = value
1173
1174 for k, v in slotstate.items():
1175 setattr(obj, k, v)
1176
1177
1178def _class_setstate(obj, state):
1179 state, slotstate = state
1180 registry = None
1181 for attrname, attr in state.items():
1182 if attrname == "_abc_impl":
1183 registry = attr
1184 else:
1185 # Note: setting attribute names on a class automatically triggers their
1186 # interning in CPython:
1187 # https://github.com/python/cpython/blob/v3.12.0/Objects/object.c#L957
1188 #
1189 # This means that to get deterministic pickling for a dynamic class that
1190 # was initially defined in a different Python process, the pickler
1191 # needs to ensure that dynamic class and function attribute names are
1192 # systematically copied into a non-interned version to avoid
1193 # unpredictable pickle payloads.
1194 #
1195 # Indeed the Pickler's memoizer relies on physical object identity to break
1196 # cycles in the reference graph of the object being serialized.
1197 setattr(obj, attrname, attr)
1198
1199 if sys.version_info >= (3, 13) and "__firstlineno__" in state:
1200 # Set the Python 3.13+ only __firstlineno__ attribute one more time, as it
1201 # will be automatically deleted by the `setattr(obj, attrname, attr)` call
1202 # above when `attrname` is "__firstlineno__". We assume that preserving this
1203 # information might be important for some users and that it not stale in the
1204 # context of cloudpickle usage, hence legitimate to propagate. Furthermore it
1205 # is necessary to do so to keep deterministic chained pickling as tested in
1206 # test_deterministic_str_interning_for_chained_dynamic_class_pickling.
1207 obj.__firstlineno__ = state["__firstlineno__"]
1208
1209 if registry is not None:
1210 for subclass in registry:
1211 obj.register(subclass)
1212
1213 # PEP-649/749: During pickling, we excluded the __annotate_func__ attribute but it
1214 # will be created by Python. Subsequently, annotations will be recreated when
1215 # __annotations__ is accessed.
1216
1217 return obj
1218
1219
1220# COLLECTION OF DATACLASS UTILITIES
1221# ---------------------------------
1222# There are some internal sentinel values whose identity must be preserved when
1223# unpickling dataclass fields. Each sentinel value has a unique name that we can
1224# use to retrieve its identity at unpickling time.
1225
1226
1227_DATACLASSE_FIELD_TYPE_SENTINELS = {
1228 dataclasses._FIELD.name: dataclasses._FIELD,
1229 dataclasses._FIELD_CLASSVAR.name: dataclasses._FIELD_CLASSVAR,
1230 dataclasses._FIELD_INITVAR.name: dataclasses._FIELD_INITVAR,
1231}
1232
1233
1234def _get_dataclass_field_type_sentinel(name):
1235 return _DATACLASSE_FIELD_TYPE_SENTINELS[name]
1236
1237
1238class Pickler(pickle.Pickler):
1239 # set of reducers defined and used by cloudpickle (private)
1240 _dispatch_table = {}
1241 _dispatch_table[classmethod] = _classmethod_reduce
1242 _dispatch_table[io.TextIOWrapper] = _file_reduce
1243 _dispatch_table[logging.Logger] = _logger_reduce
1244 _dispatch_table[logging.RootLogger] = _root_logger_reduce
1245 _dispatch_table[memoryview] = _memoryview_reduce
1246 _dispatch_table[property] = _property_reduce
1247 _dispatch_table[staticmethod] = _classmethod_reduce
1248 _dispatch_table[CellType] = _cell_reduce
1249 _dispatch_table[types.CodeType] = _code_reduce
1250 _dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce
1251 _dispatch_table[types.ModuleType] = _module_reduce
1252 _dispatch_table[types.MethodType] = _method_reduce
1253 _dispatch_table[types.MappingProxyType] = _mappingproxy_reduce
1254 _dispatch_table[weakref.WeakSet] = _weakset_reduce
1255 _dispatch_table[typing.TypeVar] = _typevar_reduce
1256 _dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce
1257 _dispatch_table[_collections_abc.dict_values] = _dict_values_reduce
1258 _dispatch_table[_collections_abc.dict_items] = _dict_items_reduce
1259 _dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce
1260 _dispatch_table[type(OrderedDict().values())] = _odict_values_reduce
1261 _dispatch_table[type(OrderedDict().items())] = _odict_items_reduce
1262 _dispatch_table[abc.abstractmethod] = _classmethod_reduce
1263 _dispatch_table[abc.abstractclassmethod] = _classmethod_reduce
1264 _dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce
1265 _dispatch_table[abc.abstractproperty] = _property_reduce
1266 _dispatch_table[dataclasses._FIELD_BASE] = _dataclass_field_base_reduce
1267
1268 dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table)
1269
1270 # function reducers are defined as instance methods of cloudpickle.Pickler
1271 # objects, as they rely on a cloudpickle.Pickler attribute (globals_ref)
1272 def _dynamic_function_reduce(self, func):
1273 """Reduce a function that is not pickleable via attribute lookup."""
1274 newargs = self._function_getnewargs(func)
1275 state = _function_getstate(func)
1276 return (_make_function, newargs, state, None, None, _function_setstate)
1277
1278 def _function_reduce(self, obj):
1279 """Reducer for function objects.
1280
1281 If obj is a top-level attribute of a file-backed module, this reducer
1282 returns NotImplemented, making the cloudpickle.Pickler fall back to
1283 traditional pickle.Pickler routines to save obj. Otherwise, it reduces
1284 obj using a custom cloudpickle reducer designed specifically to handle
1285 dynamic functions.
1286 """
1287 if _should_pickle_by_reference(obj):
1288 return NotImplemented
1289 else:
1290 return self._dynamic_function_reduce(obj)
1291
1292 def _function_getnewargs(self, func):
1293 code = func.__code__
1294
1295 # base_globals represents the future global namespace of func at
1296 # unpickling time. Looking it up and storing it in
1297 # cloudpickle.Pickler.globals_ref allow functions sharing the same
1298 # globals at pickling time to also share them once unpickled, at one
1299 # condition: since globals_ref is an attribute of a cloudpickle.Pickler
1300 # instance, and that a new cloudpickle.Pickler is created each time
1301 # cloudpickle.dump or cloudpickle.dumps is called, functions also need
1302 # to be saved within the same invocation of
1303 # cloudpickle.dump/cloudpickle.dumps (for example:
1304 # cloudpickle.dumps([f1, f2])). There is no such limitation when using
1305 # cloudpickle.Pickler.dump, as long as the multiple invocations are
1306 # bound to the same cloudpickle.Pickler instance.
1307 base_globals = self.globals_ref.setdefault(id(func.__globals__), {})
1308
1309 if base_globals == {}:
1310 # Add module attributes used to resolve relative imports
1311 # instructions inside func.
1312 for k in ["__package__", "__name__", "__path__", "__file__"]:
1313 if k in func.__globals__:
1314 base_globals[k] = func.__globals__[k]
1315
1316 # Do not bind the free variables before the function is created to
1317 # avoid infinite recursion.
1318 if func.__closure__ is None:
1319 closure = None
1320 else:
1321 closure = tuple(_make_empty_cell() for _ in range(len(code.co_freevars)))
1322
1323 return code, base_globals, None, None, closure
1324
1325 def dump(self, obj):
1326 try:
1327 return super().dump(obj)
1328 except RecursionError as e:
1329 msg = "Could not pickle object as excessively deep recursion required."
1330 raise pickle.PicklingError(msg) from e
1331
1332 def __init__(self, file, protocol=None, buffer_callback=None):
1333 if protocol is None:
1334 protocol = DEFAULT_PROTOCOL
1335 super().__init__(file, protocol=protocol, buffer_callback=buffer_callback)
1336 # map functions __globals__ attribute ids, to ensure that functions
1337 # sharing the same global namespace at pickling time also share
1338 # their global namespace at unpickling time.
1339 self.globals_ref = {}
1340 self.proto = int(protocol)
1341
1342 if not PYPY:
1343 # pickle.Pickler is the C implementation of the CPython pickler and
1344 # therefore we rely on reduce_override method to customize the pickler
1345 # behavior.
1346
1347 # `cloudpickle.Pickler.dispatch` is only left for backward
1348 # compatibility - note that when using protocol 5,
1349 # `cloudpickle.Pickler.dispatch` is not an extension of
1350 # `pickle._Pickler.dispatch` dictionary, because `cloudpickle.Pickler`
1351 # subclasses the C-implemented `pickle.Pickler`, which does not expose
1352 # a `dispatch` attribute. Earlier versions of `cloudpickle.Pickler`
1353 # used `cloudpickle.Pickler.dispatch` as a class-level attribute
1354 # storing all reducers implemented by cloudpickle, but the attribute
1355 # name was not a great choice given because it would collide with a
1356 # similarly named attribute in the pure-Python `pickle._Pickler`
1357 # implementation in the standard library.
1358 dispatch = dispatch_table
1359
1360 # Implementation of the reducer_override callback, in order to
1361 # efficiently serialize dynamic functions and classes by subclassing
1362 # the C-implemented `pickle.Pickler`.
1363 # TODO: decorrelate reducer_override (which is tied to CPython's
1364 # implementation - would it make sense to backport it to pypy? - and
1365 # pickle's protocol 5 which is implementation agnostic. Currently, the
1366 # availability of both notions coincide on CPython's pickle, but it may
1367 # not be the case anymore when pypy implements protocol 5.
1368
1369 def reducer_override(self, obj):
1370 """Type-agnostic reducing callback for function and classes.
1371
1372 For performance reasons, subclasses of the C `pickle.Pickler` class
1373 cannot register custom reducers for functions and classes in the
1374 dispatch_table attribute. Reducers for such types must instead
1375 implemented via the special `reducer_override` method.
1376
1377 Note that this method will be called for any object except a few
1378 builtin-types (int, lists, dicts etc.), which differs from reducers
1379 in the Pickler's dispatch_table, each of them being invoked for
1380 objects of a specific type only.
1381
1382 This property comes in handy for classes: although most classes are
1383 instances of the ``type`` metaclass, some of them can be instances
1384 of other custom metaclasses (such as enum.EnumMeta for example). In
1385 particular, the metaclass will likely not be known in advance, and
1386 thus cannot be special-cased using an entry in the dispatch_table.
1387 reducer_override, among other things, allows us to register a
1388 reducer that will be called for any class, independently of its
1389 type.
1390
1391 Notes:
1392
1393 * reducer_override has the priority over dispatch_table-registered
1394 reducers.
1395 * reducer_override can be used to fix other limitations of
1396 cloudpickle for other types that suffered from type-specific
1397 reducers, such as Exceptions. See
1398 https://github.com/cloudpipe/cloudpickle/issues/248
1399 """
1400 t = type(obj)
1401 try:
1402 is_anyclass = issubclass(t, type)
1403 except TypeError: # t is not a class (old Boost; see SF #502085)
1404 is_anyclass = False
1405
1406 if is_anyclass:
1407 return _class_reduce(obj)
1408 elif isinstance(obj, types.FunctionType):
1409 return self._function_reduce(obj)
1410 else:
1411 # fallback to save_global, including the Pickler's
1412 # dispatch_table
1413 return NotImplemented
1414
1415 else:
1416 # When reducer_override is not available, hack the pure-Python
1417 # Pickler's types.FunctionType and type savers. Note: the type saver
1418 # must override Pickler.save_global, because pickle.py contains a
1419 # hard-coded call to save_global when pickling meta-classes.
1420 dispatch = pickle.Pickler.dispatch.copy()
1421
1422 def _save_reduce_pickle5(
1423 self,
1424 func,
1425 args,
1426 state=None,
1427 listitems=None,
1428 dictitems=None,
1429 state_setter=None,
1430 obj=None,
1431 ):
1432 save = self.save
1433 write = self.write
1434 self.save_reduce(
1435 func,
1436 args,
1437 state=None,
1438 listitems=listitems,
1439 dictitems=dictitems,
1440 obj=obj,
1441 )
1442 # backport of the Python 3.8 state_setter pickle operations
1443 save(state_setter)
1444 save(obj) # simple BINGET opcode as obj is already memoized.
1445 save(state)
1446 write(pickle.TUPLE2)
1447 # Trigger a state_setter(obj, state) function call.
1448 write(pickle.REDUCE)
1449 # The purpose of state_setter is to carry-out an
1450 # inplace modification of obj. We do not care about what the
1451 # method might return, so its output is eventually removed from
1452 # the stack.
1453 write(pickle.POP)
1454
1455 def save_global(self, obj, name=None, pack=struct.pack):
1456 """Main dispatch method.
1457
1458 The name of this method is somewhat misleading: all types get
1459 dispatched here.
1460 """
1461 if obj is type(None): # noqa
1462 return self.save_reduce(type, (None,), obj=obj)
1463 elif obj is type(Ellipsis):
1464 return self.save_reduce(type, (Ellipsis,), obj=obj)
1465 elif obj is type(NotImplemented):
1466 return self.save_reduce(type, (NotImplemented,), obj=obj)
1467 elif obj in _BUILTIN_TYPE_NAMES:
1468 return self.save_reduce(
1469 _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj
1470 )
1471
1472 if name is not None:
1473 super().save_global(obj, name=name)
1474 elif not _should_pickle_by_reference(obj, name=name):
1475 self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj)
1476 else:
1477 super().save_global(obj, name=name)
1478
1479 dispatch[type] = save_global
1480
1481 def save_function(self, obj, name=None):
1482 """Registered with the dispatch to handle all function types.
1483
1484 Determines what kind of function obj is (e.g. lambda, defined at
1485 interactive prompt, etc) and handles the pickling appropriately.
1486 """
1487 if _should_pickle_by_reference(obj, name=name):
1488 return super().save_global(obj, name=name)
1489 elif PYPY and isinstance(obj.__code__, builtin_code_type):
1490 return self.save_pypy_builtin_func(obj)
1491 else:
1492 return self._save_reduce_pickle5(
1493 *self._dynamic_function_reduce(obj), obj=obj
1494 )
1495
1496 def save_pypy_builtin_func(self, obj):
1497 """Save pypy equivalent of builtin functions.
1498
1499 PyPy does not have the concept of builtin-functions. Instead,
1500 builtin-functions are simple function instances, but with a
1501 builtin-code attribute.
1502 Most of the time, builtin functions should be pickled by attribute.
1503 But PyPy has flaky support for __qualname__, so some builtin
1504 functions such as float.__new__ will be classified as dynamic. For
1505 this reason only, we created this special routine. Because
1506 builtin-functions are not expected to have closure or globals,
1507 there is no additional hack (compared the one already implemented
1508 in pickle) to protect ourselves from reference cycles. A simple
1509 (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note
1510 also that PyPy improved their support for __qualname__ in v3.6, so
1511 this routing should be removed when cloudpickle supports only PyPy
1512 3.6 and later.
1513 """
1514 rv = (
1515 types.FunctionType,
1516 (obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__),
1517 obj.__dict__,
1518 )
1519 self.save_reduce(*rv, obj=obj)
1520
1521 dispatch[types.FunctionType] = save_function
1522
1523
1524# Shorthands similar to pickle.dump/pickle.dumps
1525
1526
1527def dump(obj, file, protocol=None, buffer_callback=None):
1528 """Serialize obj as bytes streamed into file
1529
1530 protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
1531 pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
1532 speed between processes running the same Python version.
1533
1534 Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
1535 compatibility with older versions of Python (although this is not always
1536 guaranteed to work because cloudpickle relies on some internal
1537 implementation details that can change from one Python version to the
1538 next).
1539 """
1540 Pickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj)
1541
1542
1543def dumps(obj, protocol=None, buffer_callback=None):
1544 """Serialize obj as a string of bytes allocated in memory
1545
1546 protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
1547 pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
1548 speed between processes running the same Python version.
1549
1550 Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
1551 compatibility with older versions of Python (although this is not always
1552 guaranteed to work because cloudpickle relies on some internal
1553 implementation details that can change from one Python version to the
1554 next).
1555 """
1556 with io.BytesIO() as file:
1557 cp = Pickler(file, protocol=protocol, buffer_callback=buffer_callback)
1558 cp.dump(obj)
1559 return file.getvalue()
1560
1561
1562# Include pickles unloading functions in this namespace for convenience.
1563load, loads = pickle.load, pickle.loads
1564
1565# Backward compat alias.
1566CloudPickler = Pickler