Feed a file in pieces, and the digest doesn't change
Level 3 makes the files too big to read at once. A digest doesn't need the whole file in memory, because it can take the bytes a piece at a time.
sha = hashlib.sha256()
sha.update(b"mi")
sha.update(b"lk")
print(sha.digest() == hashlib.sha256(b"milk").digest())
True
A hash object takes the bytes in pieces. The hashlib docs promise that many update calls equal one call with all the pieces joined. So where you cut doesn't matter:
Cut of b"milk" | Calls | Digest |
|---|---|---|
| [mi][lk] | update(b"mi"), update(b"lk") | the same |
| [m][ilk] | update(b"m"), update(b"ilk") | the same |
| no cut | update(b"milk") | the same |
A file may be too big to read at once, and you never need to. Three ways to hash a file, timed on a 256 MiB file of random bytes that the operating system already had cached, with peak memory from tracemalloc:
def digest_whole(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).digest()
def digest_of(path, piece=1 << 20):
sha = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(piece):
sha.update(chunk)
return sha.digest()
def digest_by_library(path):
with open(path, "rb") as f:
return hashlib.file_digest(f, "sha256").digest()
| Time | Peak memory | |
|---|---|---|
digest_whole | 0.159 s | 256.00 MiB |
digest_of, 1 MiB pieces | 0.128 s | 2.00 MiB |
hashlib.file_digest | 0.130 s | 0.26 MiB |
All three give the same digest. Reading in pieces is no slower, and holds 2 MiB instead of 256. hashlib.file_digest, new in Python 3.11, does the same loop for you on a real file.
In the editor, write fingerprint(chunks): one SHA-256 digest, as the 32 raw bytes, of all the bytes pieces in chunks, in order. Feed every piece to one hash object, and never join them.