Skip to content

Commit 07e85ce

Browse files
committed
Simplified hashing function tpye hint and _hash_file_obj
1 parent a6fed84 commit 07e85ce

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

app/assets/hashing.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
# NOTE: this allows hashing different representations of a file-like object
1010
def blake3_hash(
11-
fp: Union[str, bytes, os.PathLike[str], os.PathLike[bytes], IO[bytes]],
11+
fp: str | IO[bytes],
1212
chunk_size: int = DEFAULT_CHUNK,
1313
) -> str:
1414
"""
@@ -19,6 +19,7 @@ def blake3_hash(
1919
``read``, ``seek``, and ``tell``. The function will seek to the start before
2020
reading and will attempt to restore the original position afterward.
2121
"""
22+
# duck typing to check if input is a file-like object
2223
if hasattr(fp, "read"):
2324
return _hash_file_obj(fp, chunk_size)
2425

@@ -27,7 +28,7 @@ def blake3_hash(
2728

2829

2930
async def blake3_hash_async(
30-
fp: Union[str, bytes, os.PathLike[str], os.PathLike[bytes], IO[bytes]],
31+
fp: str | IO[bytes],
3132
chunk_size: int = DEFAULT_CHUNK,
3233
) -> str:
3334
"""Async wrapper for ``blake3_hash_sync``.
@@ -54,13 +55,11 @@ def _hash_file_obj(file_obj: IO, chunk_size: int = DEFAULT_CHUNK) -> str:
5455
chunk_size = DEFAULT_CHUNK
5556

5657
# in case file object is already open and not at the beginning, track so can be restored after hashing
57-
orig_pos = None
58-
if hasattr(file_obj, "tell"):
59-
orig_pos = file_obj.tell()
58+
orig_pos = file_obj.tell()
6059

6160
try:
62-
if hasattr(file_obj, "seek"):
63-
# seek to the beginning before reading
61+
# seek to the beginning before reading
62+
if orig_pos != 0:
6463
file_obj.seek(0)
6564

6665
h = blake3()
@@ -72,5 +71,5 @@ def _hash_file_obj(file_obj: IO, chunk_size: int = DEFAULT_CHUNK) -> str:
7271
return h.hexdigest()
7372
finally:
7473
# restore original position in file object, if needed
75-
if hasattr(file_obj, "seek") and orig_pos is not None:
74+
if orig_pos != 0:
7675
file_obj.seek(orig_pos)

0 commit comments

Comments
 (0)