diff --git a/CHANGES.md b/CHANGES.md index 15cc4996..8a713d96 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,11 @@ In development ============== +- Include globals that are only read inside a class body defined in a + function pickled by value (class scopes load them with LOAD_NAME or + LOAD_FROM_DICT_OR_GLOBALS rather than LOAD_GLOBAL). + ([issue #609](https://github.com/cloudpipe/cloudpickle/issues/609)) + 3.1.3 ===== diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 08882306..8cbc83a7 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -394,6 +394,15 @@ def func(): _glbl_ops.append(DELETE_GLOBAL) LOAD_GLOBAL = opcode.opmap["LOAD_GLOBAL"] _glbl_ops.append(LOAD_GLOBAL) +if "LOAD_NAME" in opcode.opmap: + # Class bodies read names with LOAD_NAME instead of LOAD_GLOBAL. Names + # that do not refer to globals are filtered out by the consumers of + # _extract_code_globals, so collecting them here is harmless. + _glbl_ops.append(opcode.opmap["LOAD_NAME"]) +if "LOAD_FROM_DICT_OR_GLOBALS" in opcode.opmap: + # Class-scoped type aliases (3.12+) and class __annotate__ functions + # (3.14+) read globals with LOAD_FROM_DICT_OR_GLOBALS. + _glbl_ops.append(opcode.opmap["LOAD_FROM_DICT_OR_GLOBALS"]) GLOBAL_OPS = tuple(_glbl_ops) del _glbl_ops HAVE_ARGUMENT = dis.HAVE_ARGUMENT diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index e2097d1c..0e9b35d4 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -207,6 +207,48 @@ def foo(): self.assertTrue("exit" in foo.__code__.co_names) cloudpickle.dumps(foo) + def test_class_body_reads_globals(self): + # Non-importable namespaces force pickling by value. Names that a + # class body reads from the function's globals must be included in + # the pickled globals even though class scopes load them with + # LOAD_NAME/LOAD_FROM_DICT_OR_GLOBALS instead of LOAD_GLOBAL. + ns = {"__name__": "not_importable", "CONST": 42} + exec( + "def f():\n" + " class Rec:\n" + " q = CONST\n" + " return Rec.q\n", + ns, + ) + func = pickle_depickle(ns["f"], protocol=self.protocol) + self.assertEqual(func(), 42) + + # A class-local name shadowing a global still resolves to the + # class-local value after depickling. + ns = {"__name__": "not_importable", "CONST": 99} + exec( + "def f():\n" + " class Rec:\n" + " CONST = 1\n" + " q = CONST\n" + " return Rec.q\n", + ns, + ) + func = pickle_depickle(ns["f"], protocol=self.protocol) + self.assertEqual(func(), 1) + + def test_class_annotation_reads_globals(self): + ns = {"__name__": "not_importable", "Point": tuple} + exec( + "def f():\n" + " class Rec:\n" + " p: Point\n" + " return Rec.__annotations__['p'].__name__\n", + ns, + ) + func = pickle_depickle(ns["f"], protocol=self.protocol) + self.assertEqual(func(), "tuple") + def test_memoryview(self): buffer_obj = memoryview(b"Hello") self.assertEqual(