Claude Code for random: Randomness in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for random: Randomness in Python
AI

Claude Code for random: Randomness in Python

Published: August 12, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free