Python hash() Function and hashlib: How Hashing Works

An order-import job I reviewed used the Python hash function, hash(), to fingerprint each CSV upload. It looked fine until the job restarted and every file suddenly looked new, because hash() of a string changes between runs.

You’ll hit the same trap if you store hash() values: it’s built for dict and set lookups inside one run. Stable fingerprints come from hashlib.

Quick answer: call hash(obj) to get an integer for an immutable object, and use hashlib.sha256(data).hexdigest() when the value must be the same tomorrow.

hash((1042, "TX"))                       # int, same only within this run
hashlib.sha256(b"order=1042").hexdigest()  # same hex string every run

In this tutorial, I’ll show you the Python hash function, unhashable types, custom __hash__ and hashlib.

I ran the scripts on Python 3.12.5 in VS Code, using order IDs, SKUs and prices from a small US web store.

What does the Python hash() function return?

hash() returns an integer that dicts and sets use to find your key fast. Equal values must hash the same:

import sys

print(hash(42), hash(42.0), hash(True))
print(hash(-1), hash(-2))      # -1 is reserved, so both give -2
print(hash((1042, "TX")) == hash((1042, "TX")))
print(hash("SKU-1001"))        # a different number every run
print(sys.hash_info.width, "bit hashes")

Output:

42 42 1
-2 -2
True
208222016721981985
64 bit hashes
VS Code output of the Python hash function on an int, a float, True, -1, a tuple and a string
Small ints hash to themselves; -1 and -2 share a hash.

The string line changes every run, so yours won’t match mine. Tuples hash from their items, which is why the difference between lists, tuples, sets and dictionaries matters here.

Why does hash() give a different number every run?

Since Python 3.3, str and bytes hashes use a random seed per process (hash randomization), which blocks dict denial-of-service attacks. PYTHONHASHSEED fixes the seed:

import os
import subprocess
import sys

code = "print(hash('SKU-1001'))"
for seed in (None, None, "0", "0"):
    env = dict(os.environ)
    env.pop("PYTHONHASHSEED", None)
    if seed:
        env["PYTHONHASHSEED"] = seed
    out = subprocess.run([sys.executable, "-c", code], env=env,
                         capture_output=True, text=True).stdout
    print(f"PYTHONHASHSEED={seed or 'random':<7}", out.strip())

Output:

PYTHONHASHSEED=random  -8287555181164042858
PYTHONHASHSEED=random  3352066539734465467
PYTHONHASHSEED=0       4155151497324424999
PYTHONHASHSEED=0       4155151497324424999
VS Code output running hash('SKU-1001') in four child processes, random seed versus PYTHONHASHSEED=0
Random-seed runs differ; PYTHONHASHSEED=0 runs match.

Use PYTHONHASHSEED=0 only to reproduce a test. Lookups like checking if a key is in a Python dictionary never need it.

How to fix TypeError: unhashable type: ‘list’

Lists, dicts and sets have no hash, because a key that changes would get lost inside a dict. You’ll see four bad keys and two good ones:

prices = {"SKU-1001": 24.99}

for key in (["TX", "CA"], {"state": "TX"}, {"TX"}, (1, [2])):
    try:
        prices[key] = 0
    except TypeError as err:
        print("TypeError:", err)

prices[("TX", "CA")] = 12.50        # tuple works
prices[frozenset({"TX"})] = 8.75    # frozenset works
print(len(prices), "keys")

Output:

TypeError: unhashable type: 'list'
TypeError: unhashable type: 'dict'
TypeError: unhashable type: 'set'
TypeError: unhashable type: 'list'
3 keys
VS Code output of Python TypeError unhashable type for list, dict and set keys, then tuple and frozenset keys working
Lists, dicts, sets and a tuple holding a list all fail; tuple and frozenset keys work.

The fix is to use an immutable twin: tuple for list, frozenset for set. My guide on mutable vs immutable types in Python explains which types are which.

Make a custom class hashable with __hash__ and __eq__

By default, objects hash by identity. Once you define __eq__, Python sets __hash__ to None, so you must add it back using the same fields:

from dataclasses import dataclass

class Product:
    def __init__(self, sku, price):
        self.sku, self.price = sku, price
    def __eq__(self, other):
        return isinstance(other, Product) and self.sku == other.sku

print("Product.__hash__ is", Product.__hash__)

class HashableProduct(Product):
    def __hash__(self):
        return hash(self.sku)

cart = [HashableProduct("SKU-1001", 24.99),
        HashableProduct("SKU-2002", 9.50),
        HashableProduct("SKU-1001", 24.99)]
print(len(set(cart)), "unique products")

@dataclass(frozen=True)
class Item:
    sku: str
    price: float

print(len({Item("SKU-1001", 24.99), Item("SKU-1001", 24.99)}), "item")

Output:

Product.__hash__ is None
2 unique products
1 item
VS Code output showing Product.__hash__ is None after __eq__, a set removing a duplicate SKU, and a frozen dataclass
Two products share SKU-1001, so the set keeps 2 of 3.

Pro Tip: @dataclass(frozen=True) writes both methods for you; see the Python dataclass guide. Deduplicating like this works the same as converting a list to a set.

Hash strings and files with hashlib (SHA-256 and MD5)

hashlib gives the same digest on every machine and run, so it’s what you store. It takes bytes, so you encode strings first:

import hashlib
from pathlib import Path

order = b"order=1042;total=149.99;date=2026-03-14"
print("sha256:", hashlib.sha256(order).hexdigest())
print("md5:   ", hashlib.md5(order).hexdigest())

typo = order.replace(b"149.99", b"149.98")
print("1 char:", hashlib.sha256(typo).hexdigest())

Path("orders_2026.csv").write_bytes(b"id,total\n1042,149.99\n")
with open("orders_2026.csv", "rb") as f:
    print("file:  ", hashlib.file_digest(f, "sha256").hexdigest())

Output:

sha256: 954048dace8b9b840e1ec021a6ab771a6daaf7704ca30fe5e53991faa1f885bb
md5:    4de958b297c3e7f2a1df55e46bb4828f
1 char: 682e067c6c6fab252f2dcca7133dcc41b7bd91b7acb6194b2db5a40f6d5464c7
file:   a475d3f18e4fdae68bce705e6613b84732830dff0a28b0e4a35b43c22021da65
VS Code output of hashlib SHA-256 and MD5 digests for an order string, a one-character change and a CSV file
Changing 149.99 to 149.98 produces a completely different SHA-256 digest.

hashlib.file_digest() needs Python 3.11+. For raw file handling, see reading a binary file in Python; a digest is just a string of hexadecimal characters.

How should you hash passwords in Python?

Not with hash() or one fast SHA-256 pass. You want a slow, salted function like hashlib.pbkdf2_hmac():

import hashlib
import hmac
import os

password = b"demo-pass-2026"          # fake demo value
salt = os.urandom(16)
key = hashlib.pbkdf2_hmac("sha256", password, salt, 600_000)
print(len(salt), "byte salt,", len(key), "byte key")

attempt = hashlib.pbkdf2_hmac("sha256", b"demo-pass-2026", salt, 600_000)
print("match:", hmac.compare_digest(key, attempt))
wrong = hashlib.pbkdf2_hmac("sha256", b"demo-pass-2025", salt, 600_000)
print("match:", hmac.compare_digest(key, wrong))

Output:

16 byte salt, 32 byte key
match: True
match: False

Store the salt and key; compare with hmac.compare_digest(). Before hashing, check the input with password validation in Python.

Common errors with the Python hash function

ProblemCauseFix
Stored hash() values don’t matchString hashes are randomized per runUse hashlib.sha256()
TypeError: unhashable typeList, dict or set as a keyTuple or frozenset
Class instances not in a set__eq__ without __hash__Add __hash__ or a frozen dataclass
Strings must be encodedhashlib got a strCall .encode()

These related guides pair well with this one:

Frequently asked questions

What is the hash function in Python?

hash(), a built-in that returns an integer for a hashable object.

Why does hash() return different values each time?

String and bytes hashes are randomized per process.

Can I hash a list in Python?

No. Convert it to a tuple first: hash(tuple(my_list)).

What is the difference between hash() and hashlib?

hash() is a per-run integer for lookups; hashlib gives stable digests like SHA-256.

Is MD5 safe to use in Python?

Only as a checksum. For security, use SHA-256 or pbkdf2_hmac().

Where is hashlib documented?

See the hashlib module in the Python docs.