preserve_state#

delu.random.preserve_state()[source]#

Save the global RNG states before entering a context/function and restore it on exit.

The function saves the global RNG states in random, numpy and torch when entering a context/function and restores it on exit/return.

Note

Within a context or a function call, random sampling works as usual, i.e. it continues to be “random”.

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()
...     # Within the context, random sampling continues to be random:
...     b = f()
...     assert a != b
...
>>> # However, now, the state is reset to what it was before the context.
>>> c = f()
>>> a == c
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