Skip to content

Commit

Permalink
explicit state/hash for pathlib paths
Browse files Browse the repository at this point in the history
  • Loading branch information
albertz committed Oct 10, 2024
1 parent 11e23b7 commit 31cbaef
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
8 changes: 8 additions & 0 deletions sisyphus/hash.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import enum
import hashlib
import pathlib
from inspect import isclass, isfunction, ismemberdescriptor


Expand Down Expand Up @@ -43,6 +44,13 @@ def get_object_state(obj):
Comment: Maybe obj.__reduce__() is a better idea? is it stable for hashing?
"""

if isinstance(obj, pathlib.PurePath):
# pathlib paths have a somewhat technical internal state
# ('_drv', '_root', '_parts', '_str', '_hash', '_pparts', '_cached_cparts'),
# so we don't want to rely on this, but instead just use the string representation as state.
# https://github.com/rwth-i6/sisyphus/pull/208#issuecomment-2405560718
return str(obj)

if hasattr(obj, "__getnewargs_ex__"):
args = obj.__getnewargs_ex__()
elif hasattr(obj, "__getnewargs__"):
Expand Down
6 changes: 6 additions & 0 deletions tests/hash_unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ def test_functools_partial(self):
),
)

def test_pathlib_Path(self):
from pathlib import Path

obj = Path("/etc/passwd")
self.assertEqual(sis_hash_helper(obj), b"(PosixPath, (str, '/etc/passwd'))")


if __name__ == "__main__":
unittest.main()

0 comments on commit 31cbaef

Please sign in to comment.