hydrantosaurus.com

Putting values into buckets in Python

Useful when doing staged rollouts:

import hashlib


def assign_bucket(value: str, bucket_count: int) -> int:
    return int(hashlib.md5(value.encode("utf-8")).hexdigest(), 16) % bucket_count


def main():
    values: list[str] = ["one", "two", "three"]
    for v in values:
        bucket = assign_bucket(v, 100)
        print(f"{v} -> {bucket}")


if __name__ == "__main__":
    main()

Does not distribute to all buckets evenly, but works.

14 Feb 2023