delu.random.preserve_state#

delu.random.preserve_state()[source]#

Decorator and context manager for preserving global random state.

The function saves the global random state when entering the context and restores it on exit.

Examples

import random

f = lambda: (
    random.randint(0, 10),
    np.random.randint(10),
    torch.randint(10, (1,)).item()
)
with delu.random.preserve_state():
    a = f()
b = f()
assert a == b

@delu.random.preserve_state()
def g():
    return f()

a = g()
b = f()
assert a == b