From ba71202d484187e42ed09d9191b9e32a42ddd63d Mon Sep 17 00:00:00 2001 From: Djoume Salvetti Date: Wed, 19 Nov 2025 10:03:52 -0500 Subject: [PATCH 1/2] gh-141749 fix pure python pickle.py error handling This fix addresses error handling inconsistencies in CPython's pure Python `pickle.py` implementation to match the behavior of the C `_pickle` module. The changes make the pure Python implementation raise proper `UnpicklingError` exceptions for invalid pickle data instead of low-level `KeyError` and `IndexError` exceptions. --- Lib/pickle.py | 8 +++++++- Lib/test/test_pickle.py | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Lib/pickle.py b/Lib/pickle.py index 729c215514ad24..fe984476fed346 100644 --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -1322,12 +1322,18 @@ def load(self): if not key: raise EOFError assert isinstance(key, bytes_types) - dispatch[key[0]](self) + try: + dispatch[key[0]](self) + except KeyError: + raise UnpicklingError( + f"invalid load key, '\\x{key[0]:02x}'.") except _Stop as stopinst: return stopinst.value # Return a list of items pushed in the stack after last MARK instruction. def pop_mark(self): + if not self.metastack: + raise UnpicklingError("could not find MARK") items = self.stack self.stack = self.metastack.pop() self.append = self.stack.append diff --git a/Lib/test/test_pickle.py b/Lib/test/test_pickle.py index e2384b33345a45..d1afcb5a0cc591 100644 --- a/Lib/test/test_pickle.py +++ b/Lib/test/test_pickle.py @@ -55,7 +55,7 @@ class PyPickleTests(AbstractPickleModuleTests, unittest.TestCase): class PyUnpicklerTests(AbstractUnpickleTests, unittest.TestCase): unpickler = pickle._Unpickler - bad_stack_errors = (IndexError,) + bad_stack_errors = (pickle.UnpicklingError, IndexError) truncated_errors = (pickle.UnpicklingError, EOFError, AttributeError, ValueError, struct.error, IndexError, ImportError) From 0c0376fdf71122c5556fd0b0d302c92264ca651a Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Wed, 19 Nov 2025 15:23:31 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../next/Library/2025-11-19-15-23-30.gh-issue-141749.QRBf7O.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2025-11-19-15-23-30.gh-issue-141749.QRBf7O.rst diff --git a/Misc/NEWS.d/next/Library/2025-11-19-15-23-30.gh-issue-141749.QRBf7O.rst b/Misc/NEWS.d/next/Library/2025-11-19-15-23-30.gh-issue-141749.QRBf7O.rst new file mode 100644 index 00000000000000..85d38eeb682f3a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-11-19-15-23-30.gh-issue-141749.QRBf7O.rst @@ -0,0 +1 @@ +Pure python pickle.py error handling is more consistent with the c implementation, raising UnpicklingError exceptions for invalid pickle data instead of KeyError or IndexError.