4

I know how to set the random seed in python

random.seed([x])

Once the seed is set is there any way to read it back and figure out what value was passed to the seed() function?

Plazgoth
  • 1,242
  • 1
  • 12
  • 22
  • 1
    1. According to the docs python uses system time as the seed if no parameter is given. 2. As a workaround you can use getstate and setstate – zenpoy Oct 02 '12 at 20:03

2 Answers2

4

While the underlying algorithm for Python's Random (Mersenne Twister) is deterministic, the seed is not stored anywhere in the implementation's memory space. It is up to the caller to store the seed, if necessary.

http://docs.python.org/library/random.html#module-random

For more info on Python's implementation (or to override it with your own seed storing random class) see:

http://hg.python.org/cpython/file/0b650272f58f/Lib/random.py

and

http://hg.python.org/cpython/file/0b650272f58f/Python/random.c

mattypiper
  • 1,222
  • 8
  • 8
3

There is no way to get back the seed itself. The seed is used to update the internal state of the random number generator, and it is not directly stored anywhere.

There is a way however, to save the current state! The random module is based on the Mersenne Twister pseudo random number generator, and it is implemented in C (with the _random extension module). You can do this:

import random
r = random.Random()
# Use the r object to generate numbers
# ...
curstate = r.__getstate__()
# Use it even more..
#
r.__setstate__(curstate) # Go back to previous state

In other words, random.Random() objects can be pickled, and you can use pickled objects (or the __getstate__ / __setstate__ methods directly) to go back to a previous state.

nagylzs
  • 3,954
  • 6
  • 39
  • 70