Search code examples
pythonnumpyrandomrandom-seed

Python Local random seed


I have a random seed set at the start of my run for reproducibility. But there are a few sub-functions (e.g. random) that also use random numbers. If I used a different random number seed just for those, it affects the random seed outside of the function. Is it possible to set the random seed and use it only locally inside the function and the random state outside the function does not get affected? I believe I can always get the random state, save it and restore it. Would there be an easier option? I showed an example below.

import numpy as np

def random():
    np.random.seed(420)
    np.random.randint(1, 100)
    np.random.randint(1, 100)
    return None


np.random.seed(69)
for n in range(3):
    np.random.randint(1,100) # outputs : 55,76,74
for n in range(3):
    np.random.randint(1,100) # outputs : 91,56,21

Is it possible to make the function below also output the same thing?

np.random.seed(69)
for n in range(3):
    np.random.randint(1,100) # outputs : 55,76,74
random()
for n in range(3):
    np.random.randint(1,100) # would like it to output : 91,56,21

Solution

  • That's why there are numpy random generators and that is why they recommend using that. Just define one generator for each instance, e.g.:

    def rando(rng):
        print('function')
        print(rng.integers(1, 100))
        print(rng.integers(1, 100))
        print('end of function')
        return None
    
    
    
    rng1 = np.random.default_rng(69)
    rng2 = np.random.default_rng(420)
    
    for n in range(3):
        print(rng1.integers(1, 100)) # outputs : 6,58,67
    rando(rng2) # outputs 62, 77
    for n in range(3):
        print(rng1.integers(1, 100)) # would like it to output : 53,78,86
    

    yielding:

    6
    58
    67
    function
    62
    77
    end of function
    53
    78
    86
    

    and when you comment out the function call, you get:

    6
    58
    67
    53
    78
    86