Skip to content

pickle.py raises wrong exceptions for Invalid Data #2639

@djoume

Description

@djoume

Steps to reproduce:

import pickle

invalid_data = b"this is not valid pickle data"
try:
    pickle.loads(invalid_data)
    assert False, "Expected UnpicklingError to be raised"
except pickle.UnpicklingError:
    assert True
except IndexError:
    print("IndexError raised instead of UnpicklingError")

from unittest.mock import patch, mock_open

with patch("builtins.open", mock_open(read_data=invalid_data)):
  with open("dummy_file", "rb") as f:
    try:
      pickle.load(f)
      assert False, "Expected UnpicklingError to be raised"
    except pickle.UnpicklingError:
      assert True
    except IndexError:
        print("IndexError raised instead of UnpicklingError")

Expected (CPython behaviour): no output

Actual:

IndexError raised instead of UnpicklingError
IndexError raised instead of UnpicklingError

Note this is actually a bug in CPython's standard library: python/cpython#141749

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions