preserve_state#
- delu.random.preserve_state()[source]#
A decorator and context manager for preserving the global random generators state.
The function saves the global random generators state when entering a context/function and restores it on exit/return.
Usage
As a context manager (the state after the context is the same as before the context):
>>> import random >>> import numpy as np >>> >>> def f(): ... return random.random(), np.random.rand(), torch.rand(1).item() ... >>> with delu.random.preserve_state(): ... a = f() >>> b = f() >>> a == b True
As a decorator (the state after the call
g()
is the same as before the call):>>> @delu.random.preserve_state() ... def g(): ... return f() ... >>> a = g() >>> b = f() >>> a == b True