random.getstate / setstate
seed() can only restart a sequence from the beginning; getstate()/setstate() rewind to any point. The state is the 624-word Mersenne Twister array, the position in it, and the value gauss() has cached.
Demo
import random random.seed(42) state = random.getstate() first = [random.randint(1, 9) for _ in range(5)] random.setstate(state) again = [random.randint(1, 9) for _ in range(5)] (first, again)
Right after seeding the position is 624: the array is "used up", so the first draw regenerates all 624 words and resets the position to 0. Each random() consumes two 32-bit words, so after one call the position is 2, and after 313 calls (626 words) it has wrapped around once and is 2 again. state[2] is None because no gauss() value is cached.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| state | tuple | yes | setstate: an object returned by getstate() (version 3; version 2 tuples from old Pythons are converted). |
Return value
tuple | None — getstate: (3, tuple of 625 ints, gauss_next). setstate: None.
Common patterns
import pickle import random with open('checkpoint.pkl', 'wb') as f: pickle.dump({'step': step, 'rng': random.getstate()}, f)
import random saved = random.getstate() preview = [random.random() for _ in range(3)] random.setstate(saved)
import random clone = random.Random() clone.setstate(rng.getstate())
Examples
Pitfalls
import random random.seed(42) random.random() x = random.random() random.seed(42) random.random() == x
import random random.seed(42) random.random() saved = random.getstate() x = random.random() random.setstate(saved) random.random() == x
import random random.SystemRandom().getstate()
import random random.Random(42).getstate()[0]
When to use
- Checkpointing long simulations
- Peeking at upcoming values, or replaying a section exactly
- Copying the state of one Random into another
- Starting a repeatable run → seed()
- Independent streams → separate random.Random(seed) instances
- Exchanging states between different generator classes
Notes
FAQ
state = random.getstate() saves it, random.setstate(state) restores it. The state is a plain tuple, so it can be pickled with your other data.