diff --git a/CHANGES.md b/CHANGES.md index 15cc4996..761077d3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,10 @@ In development ============== +- Restore dynamic functions whose cloudpickle state omits the submodule list. + Loading objects written by the standard library's default pickler already + uses `pickle.load`. ([PR #596](https://github.com/cloudpipe/cloudpickle/pull/596)) + 3.1.3 ===== diff --git a/cloudpickle/cloudpickle.py b/cloudpickle/cloudpickle.py index 08882306..5a4b473d 100644 --- a/cloudpickle/cloudpickle.py +++ b/cloudpickle/cloudpickle.py @@ -1157,8 +1157,10 @@ def _function_setstate(obj, state): # the pickled function to work correctly at unpickling time. Now that these # submodules are depickled (hence imported), they can be removed from the # object's state (the object state only served as a reference holder to - # these submodules) - slotstate.pop("_cloudpickle_submodules") + # these submodules). Tolerate its absence: valid cloudpickle payloads always + # set this key, but a malformed one need not, and popping it unguarded turns + # that into an opaque KeyError. + slotstate.pop("_cloudpickle_submodules", None) obj.__globals__.update(obj_globals) obj.__globals__["__builtins__"] = __builtins__ diff --git a/tests/cloudpickle_test.py b/tests/cloudpickle_test.py index e2097d1c..0d17d7d0 100644 --- a/tests/cloudpickle_test.py +++ b/tests/cloudpickle_test.py @@ -48,6 +48,7 @@ from cloudpickle.cloudpickle import _make_empty_cell from cloudpickle.cloudpickle import _extract_class_dict, _whichmodule from cloudpickle.cloudpickle import _lookup_module_and_qualname +from cloudpickle.cloudpickle import _function_setstate from .testutils import subprocess_worker from .testutils import subprocess_pickle_echo @@ -3180,5 +3181,18 @@ def test_module_level_pickler(): assert cloudpickle.Pickler is cloudpickle.CloudPickler +def test_function_setstate_without_submodules_key(): + # #593: a payload whose slotstate lacks "_cloudpickle_submodules" must not + # crash with an opaque KeyError. Valid cloudpickle payloads always carry + # that key, but malformed ones need not, and the guard that used to allow + # for its absence was dropped when the module was consolidated. + def f(x): + return x + + _function_setstate(f, ({}, {"__globals__": {}, "__closure__": None})) + + assert f(1) == 1 + + if __name__ == "__main__": unittest.main()