Sub topic 8
Reproducible randomness with seeds and Random instances
This chapter assumes you know how to call functions and pass arguments, and that you have used random.randint and random.choice. Here you will learn why "random" numbers can repeat exactly, and how to use that in tests and experiments.
Why random numbers repeat
Python's random module produces pseudo-random numbers. A pseudo-random generator is an algorithm that starts from an internal state and computes each number from the previous state. The starting value is called the seed. The same seed gives the same state, so it gives the same sequence.
If you do not set a seed, Python seeds the generator from the operating system, so each run differs. If you set one, each run is identical.
Seeding the shared generator
The functions random.random() and random.randint() use one hidden, shared generator. random.seed() resets it.
import random
random.seed(42)
first = random.random()
random.seed(42)
second = random.random()
print(first == second) # TrueThis works for small scripts. The problem is that the generator is shared. Any other code that calls random functions, including a library you imported, advances the same state and changes your results.
Independent Random instances
random.Random(seed) creates a separate generator object. It has the same methods as the module (randint, choice, sample, shuffle and so on), and its state belongs only to it.
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 sequenceBecause the instances are independent, you can interleave calls to a and b, or call the global random functions in between, and neither sequence changes.
Passing the generator into your functions
Code that calls the global random functions directly is hard to test. Accept a generator as a parameter instead.
import random
def roll_dice(rng, count):
return [rng.randint(1, 6) for _ in range(count)]
# In a test: a fixed seed makes the result repeatable.
assert roll_dice(random.Random(3), 4) == roll_dice(random.Random(3), 4)
# In production: an unseeded generator gives a different result each run.
print(roll_dice(random.Random(), 4))A test can pass a seeded generator and compare two runs. Production code passes random.Random(), which seeds itself from the operating system.
Saving and restoring state
You can capture where a generator is in its sequence and return to that point later.
import random
rng = random.Random(10)
saved = rng.getstate()
before = [rng.randint(1, 100) for _ in range(3)]
rng.setstate(saved)
after = [rng.randint(1, 100) for _ in range(3)]
print(before == after) # TrueCommon mistakes
- Seeding inside a loop or function. Calling
random.seed(1)before every draw makes every draw return the same value. Seed once, then draw many times. - Hard-coding expected values. Only
random.random()is documented to stay stable across Python versions. Methods such aschoiceandshufflemay change between releases. Compare two runs to each other, as above, instead of comparing against a number you copied from a printout. - Assuming a seed makes data secure. A seeded generator is fully predictable by design.
Exercise
You write def shuffle_deck(rng) that returns a shuffled copy of a list of 52 cards. How do you test that the same seed always gives the same order, and why is it better than calling random.shuffle directly inside the function?
Show answer
Build two generators with the same seed, such as random.Random(5), call shuffle_deck once with each, and assert that the two results are equal. Passing the generator in keeps its state separate from the global generator, so other code that uses random cannot change the result, and production code can pass an unseeded random.Random().