-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic.py
47 lines (36 loc) · 1.15 KB
/
basic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import random
from contextlib import contextmanager
from typing import Iterator, Optional, TypeVar
T = TypeVar("T")
def identity(x: T) -> T:
return x
@contextmanager
def sandboxed_random_context() -> Iterator[None]:
"""
Enter a context that will not affect the Python random state.
This works by saving the random state at the beginning of the context
and resetting it when exiting the context.
Examples:
>>> with sandboxed_random_context():
... _ = random.random() # has no effect outside of the context
"""
random_state = random.getstate()
try:
yield
finally:
random.setstate(random_state)
@contextmanager
def temporary_random_seed(seed: Optional[int]) -> Iterator[None]:
"""
Set a random seed in a context, to avoid side effects.
Examples:
>>> with temporary_random_seed(101):
... # ``a`` will always have the same value
... a = random.random()
Args:
seed: seed, directly forwarded to random.seed(). ``None`` means using
the system time.
"""
with sandboxed_random_context():
random.seed(seed)
yield