I like messing around with random generators for productivity and creativity systems. Usually this involves functions that return a random value on each call. Even with quite a large set of possible values, duplicates occur more often than you might expect.
Here’s a quick Python decorator that keeps calling the function it decorates until it gets a value we haven’t seen so far during the current process:
def unique_results(func: Callable) -> Callable: seen = set() def wrapper(): res = func() for i in range(100): if res not in seen: seen.add(res) return res res = func() raise OverflowError("Hit random value limit") return wrapper
Then you can decorate your random result function like this:
@unique_results def random_thing() -> str: return random.choice(["Foo", "Bar", "Baz", "etc"])
I wouldn’t recommend this for use in any production application as it doesn’t attempt to be efficient, and just bails if it can’t get a unique value in 100 attempts. It’s fine for little local sandbox scripts, though.