Sub topic 8
Reproducible randomness with seeds and Random instances
This chapter assumes you can call random.randint, random.choice and random.shuffle, and that you can write functions with default arguments. It covers how to make random code repeatable, why separate random.Random objects are often better than the module-level functions, and the cases where reproducibility quietly breaks.
Why random numbers repeat
Python's random module is a pseudo-random number generator (PRNG). It does not produce true randomness. It keeps an internal state, which is a large block of numbers (the Mersenne Twister algorithm, 19937 bits of state). Each call transforms that state and returns a value derived from it.
A seed is the starting value used to set the initial state. The same seed gives the same state, and the same state gives the same sequence. Without a seed, Python initializes the state from operating system entropy, so every run differs.
Reproducibility is useful in three places:
- Tests: a test can assert on an exact result instead of "something random happened".
- Debugging: a failing run can be replayed exactly.
- Experiments and simulations: results can be compared between runs, and others can check your numbers.
Seeding the global generator
The module-level functions such as random.random() and random.randint() all share one hidden Random instance created when the module is imported. random.seed(x) resets that hidden instance.
import random
random.seed(42)
first = [random.randint(1, 6) for _ in range(5)]
random.seed(42)
second = [random.randint(1, 6) for _ in range(5)]
print(first == second) # TrueThis is quick and fine for a small script. It becomes a problem as a program grows, because every part of the program draws from the same stream. Any other code that calls random between your calls (a library, another thread, a new debug line) changes what you receive.
Independent Random instances
random.Random(seed) creates a separate generator object with its own state. The module-level functions are bound methods of a hidden instance of this same class, so an instance has all the methods you already know: random, randint, choice, sample, shuffle, and so on.
import random
a = random.Random(7)
b = random.Random(7)
rolls_a = [a.randint(1, 6) for _ in range(5)]
rolls_b = [b.randint(1, 6) for _ in range(5)]
print(rolls_a == rolls_b) # True: same seed, same sequenceInstances do not interfere with each other or with the global generator:
import random
a = random.Random(1)
b = random.Random(1)
a.random() # advance a by one draw
a.random() # and again
random.random() # draw from the global generator
print(b.random() == random.Random(1).random()) # True: b is untouchedThe last line holds because b has not been used until then. Its first draw equals the first draw of a fresh Random(1).
Passing the generator in
For testable code, accept a generator as a parameter. Production callers use the default. Tests pass a seeded instance.
import random
def roll_dice(count, rng=None):
rng = rng or random.Random()
return [rng.randint(1, 6) for _ in range(count)]
# In a test:
assert roll_dice(5, random.Random(3)) == roll_dice(5, random.Random(3))
print("deterministic")The function never touches global state. Two functions that each receive their own instance can run in any order, or in different threads, and each keeps its own sequence.
What counts as a seed
random.Random(x) and random.seed(x) accept None, int, float, str, bytes and bytearray. Other types raise TypeError in Python 3.11 and later. Older versions accepted any hashable object. That was unsafe, because string hashes change between processes.
Noneor no argument: seed from the operating system's entropy source, so the run is not repeatable.- An
intis the usual choice. - A
stris useful for deriving seeds from names. Strings are converted with a stable hash, so the same string gives the same sequence in every process.
import random
base = "experiment-A"
streams = [random.Random(f"{base}-{i}") for i in range(3)]
print([s.randint(1, 100) for s in streams] == [
random.Random(f"{base}-{i}").randint(1, 100) for i in range(3)
]) # TrueGiving each task a seed built from a base name and an index produces a separate repeatable stream per task. This avoids seeding several generators with consecutive integers by hand.
Saving and restoring state
Sometimes you want to rewind. getstate() returns a snapshot of the generator, and setstate() restores it.
import random
rng = random.Random(10)
snapshot = rng.getstate()
first = [rng.random() for _ in range(3)]
rng.setstate(snapshot)
again = [rng.random() for _ in range(3)]
print(first == again) # TrueThis is useful when you want to replay one section of a long simulation, or when you want to log the state before a failure-prone step. The state object is a tuple that you can pickle. Only restore states produced by the same Python implementation.
Where reproducibility breaks
Common causes of "my seeded run gave different results":
| Cause | What happens | Fix |
|---|---|---|
| Seeding after the draws | `random.seed(1)` placed after the first `random.random()` call has no effect on it | Seed once, before any draw |
| Shared global generator | Another module or thread consumes draws between yours | Use your own `Random` instance |
| Iterating a `set` of strings | Set order changes between processes because of hash randomization, so a seeded `shuffle` or `choice` gets items in a different order | Convert with `sorted(...)` before sampling |
| Different Python version | `random()` is stable across versions, but methods such as `randint`, `choice` and `shuffle` may change their algorithms | Record the Python version, or store the generated results |
| Different number of draws | An extra `rng.random()` shifts everything after it | Use a separate instance per concern |
| `SystemRandom` | It reads the operating system's entropy and ignores seeds | Use `Random` when you need repeatability |
The set problem is easy to miss because the code looks deterministic:
import random
names = {"ada", "grace", "linus", "guido"}
rng = random.Random(5)
# Not repeatable across processes: set order can differ.
unstable = rng.choice(list(names))
# Repeatable: the order is fixed first.
rng = random.Random(5)
stable = rng.choice(sorted(names))
print(stable)random.sample no longer accepts a set directly in Python 3.11 and later, so you have to convert it to a sequence anyway. Sort it when the result must repeat.
The guarantee Python actually makes
The documentation guarantees that if a new seeding method or generator method is added, the old sequences stay available where practical, and that random() itself produces the same values for the same seed across versions. It does not promise that every higher-level method keeps its exact output forever. For long-lived test fixtures or published results, store the generated values, or pin the Python version.
Seeds are not secrets
A seed makes a sequence predictable on purpose. Anyone who knows the seed, or who observes enough outputs of the Mersenne Twister, can compute the later values. Seeding with the current time does not fix this. For passwords, tokens and keys, use the secrets module, which is the subject of the next chapter.
Putting it together
The following function picks reproducible sample data. The caller controls the seed, and nothing global changes.
import random
def sample_users(names, k, seed):
rng = random.Random(seed)
return rng.sample(sorted(names), k)
users = {"ada", "grace", "linus", "guido", "barbara"}
print(sample_users(users, 2, seed=99) == sample_users(users, 2, seed=99)) # TrueExercise
A test seeds the global generator with random.seed(0) and then calls a helper from another library that internally uses random.random() a variable number of times. The test fails intermittently. Give the cause and a fix.
Show answer
Both the test and the library draw from the same hidden global generator, so the number of draws the library consumes shifts the values the test sees later. Replace the global calls in your own code with a dedicated random.Random(0) instance, and pass it to the code you control. That way the library's draws cannot change your sequence.
Exercise
What does this print, and why? rng = random.Random(4); s = rng.getstate(); a = rng.randint(1, 100); rng.setstate(s); b = rng.randint(1, 100); print(a == b)
Show answer
It prints True. setstate restores the exact internal state captured by getstate, so the next randint(1, 100) call repeats the same draw.
Exercise
You shuffle list(my_set) of strings with a seeded Random and get a different order on each program run. Why, and how do you fix it?
Show answer
String hashes are randomized per process, so the iteration order of a set of strings can differ between runs, and the seeded shuffle starts from a different list order. Use sorted(my_set) to get a fixed starting order before shuffling.