In this lesson, you will learn how to achieve deterministic, repeatable results in your simulations and tests by using isolated random.Random instances instead of the global random state.
The Problem with Global Randomness
When you use the global random module functions (like random.random() or random.choice()), you are relying on a single, shared source of entropy. If your code calls third-party libraries that also use the global state, the sequence of "random" numbers becomes unpredictable and impossible to replicate across different execution environments. This makes debugging simulations or verifying unit tests incredibly difficult.
The Solution: Local Instances
To gain full control, you should instantiate your own local random object. By passing a specific seed to the random.Random() constructor, you create a self-contained generator that will produce the exact same sequence of values every time it is initialized with that same seed.
import random
# Create a local generator with a fixed seed
rng = random.Random(42)
# This sequence will always be the same
results = [rng.randint(1, 100) for _ in range(5)]
print(results) # [82, 15, 3, 95, 36]
# Even if other parts of your app use 'random',
# this 'rng' instance remains isolated and predictable.
When to Use secrets
While seeding is perfect for simulations, data analysis, or testing, never use it for security-sensitive tasks like generating passwords, security tokens, or cryptographic keys.
For security, you must use the secrets module. Unlike random, secrets is designed to be cryptographically secure and does not allow for seeding. If your goal is reproducibility for logic verification, use random.Random(seed). If your goal is safety against malicious actors, use secrets.
Why this matters
By keeping your random state local, you ensure that your code is "deterministic." If a test fails, you can re-run it with the same seed to observe the exact state that caused the bug. This turns "heisenbugs"—bugs that disappear when you try to look at them—into reproducible issues you can solve with confidence.
Key Takeaway: Always use a local random.Random instance with a fixed seed for reproducible simulations, but switch to the secrets module whenever you need cryptographically secure randomness.