Random With Seed Replays The Same Draws

random.Random(seed) produces the same draws, shuffles, and samples on every replay, so tests and demos stay reproducible; unseeded instances differ.

PythonResilience

Code

pythonsnippet
20 lines
import random

# 固定种子:同一版本 Python 里序列逐次一致,测试与演示可复现
rng = random.Random(42)
print('first draw :', rng.randrange(1000))
print('next draw  :', rng.randrange(1000))

# shuffle 与 sample 走同一个流:种子相同则洗牌相同
rng = random.Random(42)
deck = list(range(5))
rng.shuffle(deck)
print('shuffled   :', deck)
print('sample     :', rng.sample(deck, 3))

# 重放:同种子重建实例,整段序列完全一致
rng2 = random.Random(42)
print('replay     :', [rng2.randrange(1000) for _ in range(2)])

# 不同种子分岔;Random() 不带种子每次都不同
print('other seed :', random.Random(7).randrange(1000))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

first draw : 654
next draw  : 114
shuffled   : [3, 1, 2, 4, 0]
sample     : [1, 0, 3]
replay     : [654, 114]
other seed : 331

How the snippet works

Top-level bindings rng, deck, rng2 hold the demo state — nothing sits inside a function scope.

Using it

The demo output is labeled (first draw :, other seed :); each label names the call that printed it.

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Every import resolves inside the standard library — `random`. Its state lives in module-level bindings: `rng`, `deck`, `rng2`.