Datasets:

ArXiv:
File size: 1,138 Bytes
d8d4369
 
 
 
 
 
 
 
 
950b2da
 
 
 
 
 
d8d4369
 
950b2da
 
 
 
 
 
 
 
 
 
 
 
 
 
d8d4369
 
 
 
950b2da
d8d4369
 
 
 
950b2da
d8d4369
 
 
 
 
950b2da
d8d4369
 
950b2da
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
48
49
50
51
import contextlib
import random as python_random
import string
import threading

__default_seed__ = 42
_thread_local = threading.local()


def get_seed():
    try:
        return _thread_local.seed
    except AttributeError:
        _thread_local.seed = __default_seed__
        return _thread_local.seed


def get_random():
    try:
        return _thread_local.random
    except AttributeError:
        _thread_local.random = python_random.Random(get_seed())
        return _thread_local.random


random = get_random()


def set_seed(seed):
    _thread_local.seed = seed
    get_random().seed(seed)


def get_random_string(length):
    letters = string.ascii_letters
    return "".join(get_random().choice(letters) for _ in range(length))


@contextlib.contextmanager
def nested_seed(sub_seed=None):
    old_state = get_random().getstate()
    old_global_seed = get_seed()
    sub_seed = sub_seed or get_random_string(10)
    new_global_seed = str(old_global_seed) + "/" + sub_seed
    set_seed(new_global_seed)
    try:
        yield get_random()
    finally:
        set_seed(old_global_seed)
        get_random().setstate(old_state)