How to use Python random number generator with local seed?

The Python case seems global, so the modules modifying it will influence each other.

Although, of course, there are many third-party modules, is there a way to use the standard Python library for a random number local to the context.

(without using random.get/setstate , which can be problematic when mixing code from different modules).

Sort of...

 r = random.context(seed=42) number = r.randint(10, 20) 

Where each module can use its own random context.

+5
source share
1 answer

From the docs :

The functions provided by this module are actually related methods of the hidden instance of the random.Random class. You can create your own instances of Random to get generators that do not share state.

Create your own instance of random.Random and use it.

 rng = random.Random(42) number = rng.randint(10, 20) 
+8
source

All Articles