Python’s random module generates pseudo-random numbers using the Mersenne Twister. import random. random: random.random() → float in [0.0, 1.0). randint: random.randint(a, b) → int in [a, b] inclusive. randrange: random.randrange(start, stop, step). uniform: random.uniform(a, b) → float in [a, b]. choice: random.choice(seq) → one element. choices: random.choices(population, weights=None, k=1) → list with replacement; supports cum_weights. sample: random.sample(population, k) → list without replacement (no duplicates). shuffle: random.shuffle(seq) — in-place shuffle. gauss: random.gauss(mu, sigma) — not thread-safe. normalvariate: random.normalvariate(mu, sigma) — thread-safe Gaussian. expovariate: random.expovariate(lambd) — exponential; mean = 1/lambd. triangular: random.triangular(low, high, mode). betavariate/gammavariate/lognormvariate/vonmisesvariate/paretovariate/weibullvariate: other distributions. seed: random.seed(a) — fixed integer or string for reproducibility. getstate/setstate: state = random.getstate() / random.setstate(state) — snapshot and restore. Random class: rng = random.Random(seed) — isolated instance; thread-safe and seeded independently. SystemRandom: random.SystemRandom() — wraps os.urandom; not seeable. secrets module: secrets.token_hex(16), secrets.choice(), secrets.randbelow() — for passwords and tokens. Claude Code generates test fixtures, Monte Carlo simulations, lottery systems, A/B test assignments, and synthetic dataset generators.
CLAUDE.md for random
## random Stack
- Stdlib: import random
- Float: random.random() # [0, 1)
- Int: random.randint(1, 100) # inclusive
- Pick: random.choice(seq) # one item
- Weights: random.choices(pop, weights=[3,1,1], k=5)
- Unique: random.sample(pop, k=10) # no replacement
- Shuffle: random.shuffle(lst) # in-place
- Seed: random.seed(42) # reproducible
- Secure: import secrets; secrets.token_hex(32)
random Sampling and Simulation Pipeline
# app/randutil.py — seeded RNG, weighted picks, fixtures, Monte Carlo, samples
from __future__ import annotations
import math
import random
import string
import uuid
from collections import Counter
from dataclasses import dataclass, field
from typing import Any, TypeVar
T = TypeVar("T")
# ─────────────────────────────────────────────────────────────────────────────
# 1. Seeded generator
# ─────────────────────────────────────────────────────────────────────────────
def make_rng(seed: int | str | None = None) -> random.Random:
"""
Create an isolated Random instance with an optional seed.
Use isolation to avoid polluting the global random state.
Example:
rng = make_rng(42) # reproducible
rng = make_rng() # random seed
vals = [rng.randint(1, 100) for _ in range(5)]
"""
return random.Random(seed)
def with_seed(seed: int | str, fn: Any, *args: Any, **kwargs: Any) -> Any:
"""
Call fn under a fixed global seed; restore original state afterward.
Example:
result = with_seed(42, random.sample, range(100), 10)
"""
state = random.getstate()
random.seed(seed)
try:
return fn(*args, **kwargs)
finally:
random.setstate(state)
# ─────────────────────────────────────────────────────────────────────────────
# 2. Selection and sampling
# ─────────────────────────────────────────────────────────────────────────────
def weighted_choice(items: list[T], weights: list[float], rng: random.Random | None = None) -> T:
"""
Choose one item from items according to relative weights.
Example:
tier = weighted_choice(["free", "pro", "enterprise"], [70, 25, 5])
"""
_rng = rng or random
return _rng.choices(items, weights=weights, k=1)[0]
def weighted_sample(
items: list[T],
weights: list[float],
k: int,
rng: random.Random | None = None,
) -> list[T]:
"""
Sample k items with replacement using weights.
Example:
picks = weighted_sample(ad_ids, impressions, k=1000)
"""
_rng = rng or random
return _rng.choices(items, weights=weights, k=k)
def sample_without_replace(
population: list[T],
k: int,
rng: random.Random | None = None,
) -> list[T]:
"""
Sample k unique items from population without replacement.
Example:
test_users = sample_without_replace(all_users, k=50)
"""
_rng = rng or random
return _rng.sample(population, k=min(k, len(population)))
def shuffled(seq: list[T], rng: random.Random | None = None) -> list[T]:
"""
Return a shuffled copy without modifying the original.
Example:
cards = shuffled(deck, rng=make_rng(seed))
"""
_rng = rng or random
copy = list(seq)
_rng.shuffle(copy)
return copy
def one_of(*items: T, rng: random.Random | None = None) -> T:
"""
Pick one element from the given positional arguments.
Example:
status = one_of("active", "inactive", "pending")
"""
_rng = rng or random
return _rng.choice(items)
# ─────────────────────────────────────────────────────────────────────────────
# 3. Random string / ID generators
# ─────────────────────────────────────────────────────────────────────────────
def rand_string(
length: int = 12,
chars: str = string.ascii_lowercase + string.digits,
rng: random.Random | None = None,
) -> str:
"""
Generate a random string of given length.
Example:
token = rand_string(32)
slug = rand_string(8, string.ascii_lowercase)
"""
_rng = rng or random
return "".join(_rng.choices(chars, k=length))
def rand_hex(n_bytes: int = 16) -> str:
"""Random hex string (uses random, NOT cryptographically secure)."""
return "%0*x" % (n_bytes * 2, random.getrandbits(n_bytes * 8))
def rand_email(rng: random.Random | None = None) -> str:
"""Generate a plausible fake email for test fixtures."""
_rng = rng or random
user = rand_string(8, string.ascii_lowercase, rng=_rng)
domain = rand_string(6, string.ascii_lowercase, rng=_rng)
tld = _rng.choice(["com", "net", "org", "io"])
return f"{user}@{domain}.{tld}"
# ─────────────────────────────────────────────────────────────────────────────
# 4. Numeric distributions
# ─────────────────────────────────────────────────────────────────────────────
def rand_normal(
mu: float = 0.0,
sigma: float = 1.0,
*,
lo: float | None = None,
hi: float | None = None,
rng: random.Random | None = None,
) -> float:
"""
Sample from a normal distribution; optionally clamp to [lo, hi].
Example:
height = rand_normal(170, 10, lo=120.0, hi=220.0)
"""
_rng = rng or random
val = _rng.normalvariate(mu, sigma)
if lo is not None and val < lo:
val = lo
if hi is not None and val > hi:
val = hi
return val
def rand_int_weighted(weights: dict[int, float], rng: random.Random | None = None) -> int:
"""
Sample an integer with given relative weights.
Example:
roll = rand_int_weighted({1:1, 2:1, 3:1, 4:1, 5:1, 6:1}) # fair die
bad = rand_int_weighted({1:5, 2:3, 3:1, 4:1}) # loaded die
"""
_rng = rng or random
keys = list(weights)
return _rng.choices(keys, weights=[weights[k] for k in keys], k=1)[0]
def rand_bool(p: float = 0.5, rng: random.Random | None = None) -> bool:
"""
Return True with probability p.
Example:
user_is_active = rand_bool(p=0.8) # 80% active
"""
_rng = rng or random
return _rng.random() < p
def noise(amplitude: float = 1.0, rng: random.Random | None = None) -> float:
"""Uniform noise in [-amplitude, amplitude]."""
_rng = rng or random
return _rng.uniform(-amplitude, amplitude)
# ─────────────────────────────────────────────────────────────────────────────
# 5. Monte Carlo and simulation
# ─────────────────────────────────────────────────────────────────────────────
def estimate_pi(n_samples: int = 1_000_000, seed: int | None = None) -> float:
"""
Estimate π using Monte Carlo sampling.
Example:
pi_approx = estimate_pi(1_000_000)
abs(pi_approx - math.pi) < 0.01 # typically True
"""
rng = make_rng(seed)
inside = sum(
1 for _ in range(n_samples)
if rng.random() ** 2 + rng.random() ** 2 <= 1.0
)
return 4 * inside / n_samples
def bootstrap_mean(
data: list[float],
n_resamples: int = 1000,
seed: int | None = None,
) -> tuple[float, float, float]:
"""
Bootstrap estimate of mean with 95% confidence interval.
Returns (mean, ci_low, ci_high).
Example:
mean, lo, hi = bootstrap_mean(response_times)
print(f"mean={mean:.2f} ms 95% CI=[{lo:.2f}, {hi:.2f}]")
"""
rng = make_rng(seed)
n = len(data)
means = sorted(
sum(rng.choices(data, k=n)) / n
for _ in range(n_resamples)
)
lo_idx = int(0.025 * n_resamples)
hi_idx = int(0.975 * n_resamples)
return sum(data) / n, means[lo_idx], means[hi_idx]
def simulate_ab_test(
conversion_a: float,
conversion_b: float,
n_visitors: int = 1000,
seed: int | None = None,
) -> dict[str, Any]:
"""
Simulate an A/B test with given true conversion rates.
Example:
result = simulate_ab_test(0.05, 0.07, n_visitors=500)
print(result)
"""
rng = make_rng(seed)
a_visits = n_visitors // 2
b_visits = n_visitors - a_visits
a_converts = sum(1 for _ in range(a_visits) if rng.random() < conversion_a)
b_converts = sum(1 for _ in range(b_visits) if rng.random() < conversion_b)
return {
"variant_a": {"visits": a_visits, "converts": a_converts,
"rate": round(a_converts / a_visits, 4)},
"variant_b": {"visits": b_visits, "converts": b_converts,
"rate": round(b_converts / b_visits, 4)},
"b_lift": round((b_converts / b_visits) / (a_converts / a_visits) - 1, 4)
if a_converts else float("inf"),
}
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("=== random demo ===")
print("\n--- seeded generator ---")
rng = make_rng(42)
vals = [rng.randint(1, 100) for _ in range(5)]
print(f" seeded(42) ints: {vals}")
rng2 = make_rng(42)
vals2 = [rng2.randint(1, 100) for _ in range(5)]
print(f" same seed again: {vals2} equal={vals == vals2}")
print("\n--- weighted_choice ---")
tiers = ["free", "pro", "enterprise"]
weights = [70, 25, 5]
pick_counts = Counter(weighted_choice(tiers, weights) for _ in range(1000))
print(f" distribution over 1000 picks: {dict(pick_counts)}")
print("\n--- shuffled ---")
deck = list(range(1, 14))
s = shuffled(deck, rng=make_rng(7))
print(f" shuffled deck (first 7): {s[:7]}")
print(f" original unchanged: {deck[:7]}")
print("\n--- random strings ---")
print(f" rand_string(12): {rand_string(12)}")
print(f" rand_string(8, alpha): {rand_string(8, string.ascii_letters)}")
print(f" rand_email: {rand_email()}")
print("\n--- distributions ---")
heights = [rand_normal(170, 10, lo=100.0, hi=220.0) for _ in range(5)]
print(f" 5 heights: {[round(h, 1) for h in heights]}")
bools = [rand_bool(0.75) for _ in range(10)]
print(f" p=0.75 bools: {bools} trues={sum(bools)}/10")
print("\n--- estimate_pi ---")
pi_est = estimate_pi(500_000, seed=99)
print(f" π ≈ {pi_est} error={abs(pi_est - math.pi):.6f}")
print("\n--- bootstrap_mean ---")
import random as rlib
rlib.seed(0)
data = [rlib.gauss(100, 15) for _ in range(200)]
mean, lo, hi = bootstrap_mean(data, n_resamples=500, seed=1)
print(f" mean={mean:.2f} 95% CI=[{lo:.2f}, {hi:.2f}]")
print("\n--- simulate_ab_test ---")
result = simulate_ab_test(0.05, 0.07, n_visitors=2000, seed=42)
print(f" A: {result['variant_a']}")
print(f" B: {result['variant_b']}")
print(f" B lift: {result['b_lift']:+.1%}")
print("\n=== done ===")
For the secrets alternative — secrets (Python 3.6+) uses os.urandom() to generate cryptographically secure random values: secrets.token_hex(32), secrets.token_urlsafe(32), secrets.choice(alphabet), secrets.randbelow(n); random uses the Mersenne Twister which is fast but predictable once seeded and unsuitable for security — use secrets for all authentication tokens, password generation, CSRF nonces, API keys, and any value that must be unpredictable to adversaries; use random for simulations, test data, game logic, and statistical sampling where speed and reproducibility (via seed) matter. For the numpy.random alternative — numpy.random.Generator (use rng = np.random.default_rng(seed)) generates random arrays at C speed with many distributions not in stdlib (rng.dirichlet, rng.multinomial, rng.multivariate_normal); it also supports rng.choice(array, replace=False) for large-population samples without loading everything into memory — use numpy.random for vectorized sampling over arrays, machine learning experiments, and large-scale Monte Carlo simulations; use random for scalar sampling, game logic, and tests that must not depend on NumPy. The Claude Skills 360 bundle includes random skill sets covering make_rng()/with_seed() seeded generator utilities, weighted_choice()/weighted_sample()/sample_without_replace()/shuffled()/one_of() selection helpers, rand_string()/rand_hex()/rand_email() string generators, rand_normal()/rand_int_weighted()/rand_bool()/noise() distribution helpers, and estimate_pi()/bootstrap_mean()/simulate_ab_test() simulation and statistics. Start with the free tier to try random sampling patterns and random pipeline code generation.