Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pickling / Unpickling leads to inconsistent hash value #284

Closed
matthiasdiener opened this issue Dec 4, 2023 · 0 comments · Fixed by #287
Closed

Pickling / Unpickling leads to inconsistent hash value #284

matthiasdiener opened this issue Dec 4, 2023 · 0 comments · Fixed by #287

Comments

@matthiasdiener
Copy link
Contributor

matthiasdiener commented Dec 4, 2023

Running the following program twice can lead to inconsistent hash values due to restoring the hash from the pickled file (which might differ from the hash value when creating the same immutabledict from scratch):

from pickle import dump, load
from immutabledict import immutabledict

i1  = immutabledict({"a": "1", "b": "2", "c": "3"})
hash(i1)  # Force creating a cached hash value

try:
    # Second run: load pickle file
    with open("pickle_imm.pkl", "rb") as f:
        i2 = load(f)
except FileNotFoundError:
    # First run: create pickle file
    i2 = immutabledict({"a": "1", "b": "2", "c": "3"})
    with open("pickle_imm.pkl", "wb") as f:
        dump(i1, f)

assert i1 == i2
print(hash(i1), hash(i2))
assert hash(i1) == hash(i2)  # Fails on the second run: immutabledicts compare equal, but their hash values are different!
$ python pickletest.py
1128449412753896495 1128449412753896495
$ python pickletest.py
-5549929714807656641 1128449412753896495
Traceback (most recent call last):
  File "/Users/mdiener/Work/orderedsets/pickletest.py", line 24, in <module>
    assert hash(i1) == hash(i2)
           ^^^^^^^^^^^^^^^^^^^^
AssertionError

This mostly affects situations where strings, class types, etc. are stored in the immutabledict, which do not have stable hash values across Python invocations.

There are a few potential solutions:

@matthiasdiener matthiasdiener changed the title PIckling / Unpickling leads to inconsistent hash value Pickling / Unpickling leads to inconsistent hash value Dec 6, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant