lonelyenvoy/python-memoization

easy way to handle random_seed-like paramaters

spisakt opened this issue · 0 comments

In the numpy-universe stochastic functions's seed can be either fixed by setting it to an int, or deterministic behavior can be switched off by setting the seed to None.

My workaround to ensure the correct behavior is:

def my_keymaker(<the whole signature>, random_seed=None):
    if random_seed is None:
       random_seed = np.random.normal()
    return <usual key for all parameters>, random_seed

@cached(custom_key_maker=my_keymaker)
def function_with_long_signature(<the whole signature>, random_seed=None)

I understand, with this approach numpy (or equivalent) receives None (and not the random float generated in the keymaker) but at the same time, we force to have new hash every time random seed is None.

This approach seems to work nicely but doesn't look very elegant, especially if the function has a long signature...

Any more comfortable way to disable cache when certain parameters take certain values?