4

Per How to generate a repeatable random number sequence? it's possible to set the state of the random module such that you can expect the subsequent calls to randint to return the same number.

One limitation I see with this approach is that the state is set at the module level (essentially a global variable) so it seems impossible to create several streams/iterators of random numbers that would be repeatable (but the streams' calls can be interleaved arbitrarily) with the current mechanism. Are there any workarounds/alternatives libraries to that would enable this?

Community
  • 1
  • 1
Maxim Khesin
  • 597
  • 4
  • 10
  • See this answer in the linked question: https://stackoverflow.com/a/9024521/395029 – Brent Aug 04 '20 at 19:31
  • Does this answer your question? [How to generate a repeatable random number sequence?](https://stackoverflow.com/questions/9023660/how-to-generate-a-repeatable-random-number-sequence) – Brent Aug 04 '20 at 19:31

2 Answers2

8

It doesn't have to maintain state at the module level -- see the docs for the random module:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state. This is especially useful for multi-threaded programs, creating a different instance of Random for each thread, and using the jumpahead() method to make it likely that the generated sequences seen by each thread don’t overlap.

bgporter
  • 35,114
  • 8
  • 59
  • 65
5

random.Random() is what you're looking for.

http://hg.python.org/cpython/file/2.7/Lib/random.py#l72

All the random.* module-level functions are simply proxies of a shared Random() instance that lives at random._inst.

http://hg.python.org/cpython/file/2.7/Lib/random.py#l879

For your situation, all you'd do is instantiate N random.Random() instances; they will have independent internal RNG states and can be seeded/consumed without affecting one another.

In fact, I consider it a best practice to create your own Random() instances for non-trivial applications, specifically so it can be easily made repeatable if there's a state-dependent bug, etc. Particularly in test suites, this can be invaluable.

AdamKG
  • 13,678
  • 3
  • 38
  • 46