Bloom Filter for Membership Tests

Use a Bloom filter to rule out absent keys with no false negatives, trading a small false-positive rate for large memory savings.

PythonResilience

Code

pythonsnippet
23 lines
import hashlib
from typing import Iterable


class BloomFilter:
    def __init__(self, size: int, hash_count: int) -> None:
        if size <= 0 or hash_count <= 0:
            raise ValueError("size and hash_count must be positive")
        self.size = size
        self.hash_count = hash_count
        self.bits = bytearray(size)

    def _positions(self, item: str) -> Iterable[int]:
        for index in range(self.hash_count):
            digest = hashlib.sha256(f"{index}:{item}".encode()).digest()
            yield int.from_bytes(digest[:4], "big") % self.size

    def add(self, item: str) -> None:
        for position in self._positions(item):
            self.bits[position] = 1

    def might_contain(self, item: str) -> bool:
        return all(self.bits[position] == 1 for position in self._positions(item))

What the code does

The working surface is the class BloomFilter and the functions __init__, _positions, add and might_contain — everything else is wiring.

Iteration happens inside for index in range(self.hash_count) — everything outside it runs once. Invalid states are rejected up front: it throws ValueError instead of continuing with bad data.

Watch out for

  • The guard size <= 0 or hash_count <= 0 short-circuits the flow with an early raise when its condition holds.

Applying it

Entry signature: def add(self, item: str) -> None

The surface worth importing is add; the helpers around it are private to the snippet.

Statements that matter

def __init__(self, size: int, hash_count: int) -> None:
    if size <= 0 or hash_count <= 0:
        raise ValueError("size and hash_count must be positive")
    self.size = size
    self.hash_count = hash_count
    self.bits = bytearray(size)
def add(self, item: str) -> None:
    for position in self._positions(item):
        self.bits[position] = 1
def _positions(self, item: str) -> Iterable[int]:
    for index in range(self.hash_count):
        digest = hashlib.sha256(f"{index}:{item}".encode()).digest()
        yield int.from_bytes(digest[:4], "big") % self.size

Interactive Tools for This Topic

FAQ

What happens on invalid input?
It throws `ValueError` before any real work runs, via the guard `size <= 0 or hash_count <= 0` — handle it at the call site or let it propagate deliberately.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `__init__`, `_positions`, `add` at load time.