22/40
Part 4 of 7 · DigestsLearn and do

A digest is a key for a whole file

Two files of the same size can still differ, so the content has to decide. But the content can't be the key. A 2 GiB file as a dict key is 2 GiB held in memory, and comparing two such keys reads both.

SHA-256 gives 32 bytes for any input, and the same bytes on every run

import hashlib

print(hashlib.sha256(b"milk").hexdigest())
print(hashlib.sha256(b"Milk").hexdigest())
8825e76530f87ff5c737b3254c6936bc0a90bba3a10a91bbba739268208d378a
8189b8409b18b1ef215ec2f2d8da515cdc7cc21a4b7cd35482b66bede2275d02

A digest is a short value that stands for the content. It comes from a cryptographic hash function, like SHA-256 in hashlib. Any number of bytes go in, and 32 come out. Change a single byte, and you get a completely different digest.

.digest() gives the 32 raw bytes. .hexdigest() gives the same as 64 hex characters. Either one is a fine key.

Why not Python's own hash()? It isn't built for this, for two reasons.

First, it's 64 bits. Among a billion files, the chance that two share a value is about 3 in 100, as the follow-ups work out.

Predict

You print hash("milk") in two fresh Python processes. Do you get the same number?

Pick an answer above to see the rest