python: add type hints

This commit is contained in:
Max Kellermann
2023-09-16 23:23:18 +02:00
parent dd89ea4505
commit 3f2016e552
9 changed files with 68 additions and 54 deletions

@ -1,6 +1,7 @@
import hashlib
from typing import cast, Any, BinaryIO
def feed_file(h, f):
def feed_file(h: Any, f: BinaryIO) -> None:
"""Feed data read from an open file into the hashlib instance."""
while True:
@ -10,20 +11,20 @@ def feed_file(h, f):
break
h.update(data)
def feed_file_path(h, path):
def feed_file_path(h: Any, path: str) -> None:
"""Feed data read from a file (to be opened by this function) into the hashlib instance."""
with open(path, 'rb') as f:
feed_file(h, f)
def file_digest(algorithm, path):
def file_digest(algorithm: Any, path: str) -> str:
"""Calculate the digest of a file and return it in hexadecimal notation."""
h = algorithm()
feed_file_path(h, path)
return h.hexdigest()
return cast(str, h.hexdigest())
def guess_digest_algorithm(digest):
def guess_digest_algorithm(digest: str) -> Any:
l = len(digest)
if l == 32:
return hashlib.md5
@ -36,7 +37,7 @@ def guess_digest_algorithm(digest):
else:
return None
def verify_file_digest(path, expected_digest):
def verify_file_digest(path: str, expected_digest: str) -> bool:
"""Verify the digest of a file, and return True if the digest matches with the given expected digest."""
algorithm = guess_digest_algorithm(expected_digest)