random.Random
random.randint() and friends are bound methods of one hidden Random() shared by every module in your program. An instance of your own has its own state: seeding it, or other code drawing from the global one, cannot disturb each other.
Demo
import random a = random.Random(1) b = random.Random(2) ([a.randint(1, 6) for _ in range(5)], [b.randint(1, 6) for _ in range(5)])
Random(42) gives 6, 1, 1, 6, 3 whether or not the global generator was reseeded in between, and it is the same sequence random.seed(42) would give the module functions: they are the same class. Two instances with the same seed produce identical sequences; different seeds give unrelated ones.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| x | None | int | float | str | bytes | bytearray | no (None) | The seed, passed to self.seed(x). Other types raise TypeError since 3.11. |
Return value
Random — A new generator seeded with x (os.urandom() when x is None).
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| VERSION | int | Class attribute 3: the first item of getstate(), checked by setstate(). |
| gauss_next | float | None | Instance attribute: the second value cached by gauss(). |
Common patterns
import random class Dealer: def __init__(self, seed=None): self.rng = random.Random(seed) def deal(self, deck, n): return self.rng.sample(deck, n)
import random import threading local = threading.local() def rng(): if not hasattr(local, "rng"): local.rng = random.Random() return local.rng
import random class MyRandom(random.Random): def random(self): return my_source() / 2 ** 53 def getrandbits(self, k): return my_bits(k)
Examples
Pitfalls
import random def roll(): return random.Random(42).randint(1, 6) [roll() for _ in range(5)]
import random rng = random.Random(42) def roll(): return rng.randint(1, 6) [roll() for _ in range(5)]
import random rng = random.Random(1) random.seed(42) rng.random() == 0.6394267984578837
import random rng = random.Random(1) rng.seed(42) rng.random() == 0.6394267984578837
When to use
- Library and test code that needs reproducible randomness without touching the global generator
- Several independent streams (per player, per thread, per simulation run)
- Subclassing to plug in another core generator
- Security → secrets, or SystemRandom
- Quick scripts where the module functions are enough
Notes
FAQ
The class that implements the Mersenne Twister generator. The module-level functions are methods of one hidden instance; random.Random(seed) creates another, independent one with the same methods (randint, choice, shuffle, gauss, …).