Skip to content

Instantly share code, notes, and snippets.

@VictorDarvariu
Created February 5, 2020 10:11
Show Gist options
  • Select an option

  • Save VictorDarvariu/6cede9c79900c6215b5f848993d283c6 to your computer and use it in GitHub Desktop.

Select an option

Save VictorDarvariu/6cede9c79900c6215b5f848993d283c6 to your computer and use it in GitHub Desktop.
Example of managing NumPy seed with contextmanager
import contextlib
import numpy as np
# For info on contextlib, see https://docs.python.org/3/library/contextlib.html
@contextlib.contextmanager
def local_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)
if __name__ == '__main__':
my_seed = 42
with local_seed(my_seed):
value = np.random.rand(1)
print(f"sampled {value} using seed {my_seed}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment