Debian Codegraph @

tests/generate_old_pickles.py

raw
1 """scripts reproducing pickles used to test cloudpickle backward compat support
2
3
4 This file contains a few python scripts that generate pickles of canonical
5 objects whose pickling is supported by cloudpickle (dynamic functions, enums,
6 classes, modules etc). These scripts must be run with an "old" version of
7 cloudpickle. When testing, the generated pickle files are depickled using the
8 active cloudpickle branch to make sure that cloudpickle is able to depickle old
9 cloudpickle files.
10 """
11
12 import sys
13
14 from pathlib import Path
15 from enum import IntEnum
16 from types import ModuleType
17 from typing import TypeVar, Generic
18
19 import cloudpickle
20
21 PYTHON_INFO = "{}_{}{}".format(
22 sys.implementation.name, sys.version_info.major, sys.version_info.minor
23 )
24
25 PICKLE_DIRECTORY = Path(__file__).parent / "old_pickles" / PYTHON_INFO
26
27
28 def dump_obj(obj, filename):
29 with open(str(PICKLE_DIRECTORY / filename), "wb") as f:
30 cloudpickle.dump(obj, f)
31
32
33 def nested_function_factory():
34 a = 1
35
36 def nested_function(b):
37 return a + b
38
39 return nested_function
40
41
42 if __name__ == "__main__":
43 PICKLE_DIRECTORY.mkdir(parents=True)
44
45 # simple dynamic function
46 def simple_func(x: int, y=1):
47 return x + y
48
49 dump_obj(simple_func, "simple_func.pkl")
50
51 # simple dynamic class
52 class SimpleClass:
53 def __init__(self, attribute):
54 self.attribute = attribute
55
56 dump_obj(SimpleClass, "simple_class.pkl")
57
58 # simple dynamic module
59 dynamic_module = ModuleType("dynamic_module")
60 s = """if 1:
61 def f(x, y=1):
62 return x + y
63 """
64 exec(s, vars(dynamic_module))
65 assert dynamic_module.f(2, 1) == 3
66 dump_obj(dynamic_module, "simple_module.pkl")
67
68 # simple dynamic Enum
69 class DynamicEnum(IntEnum):
70 RED = 1
71 BLUE = 2
72
73 dump_obj(DynamicEnum, "simple_enum.pkl")
74
75 # complex dynanic function/classes involing various typing annotations
76 # supported since cloudpickle 1.4
77 T = TypeVar("T")
78
79 class MyClass(Generic[T]):
80 def __init__(self, attribute: T):
81 self.attribute = attribute
82
83 dump_obj(MyClass, "class_with_type_hints.pkl")
84
85 def add(x: MyClass[int], y: MyClass[int]):
86 return MyClass(x.attribute + y.attribute)
87
88 dump_obj([MyClass, add], "function_with_type_hints.pkl")
89
90 # Locally defined closure
91 nested_function = nested_function_factory()
92 dump_obj(nested_function, "nested_function.pkl")
93
94 # Store the cloudpickle version used to generate the pickles
95 version_file = PICKLE_DIRECTORY / "cloudpickle_version.txt"
96 version_file.write_text(cloudpickle.__version__)