24/40
Part 4 of 7 · DigestsLearn and do

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"CallsDigest
[mi][lk]update(b"mi"), update(b"lk")the same
[m][ilk]update(b"m"), update(b"ilk")the same
no cutupdate(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()
TimePeak memory
digest_whole0.159 s256.00 MiB
digest_of, 1 MiB pieces0.128 s2.00 MiB
hashlib.file_digest0.130 s0.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.