Python provides two distinct random generation modules: random (PRNG based on the Mersenne Twister for simulations/games) and secrets (CSPRNG for cryptographically secure tokens and passwords).
flowchart TD
A["Randomness Needs"] --> B{"Cryptographic / Security Sensitive?"}
B -- "No (Games, Simulations, Sampling)" --> C["random Module (Mersenne Twister PRNG)"]
B -- "Yes (Tokens, Passwords, Keys)" --> D["secrets Module (OS CSPRNG)"]
random: Fast pseudo-random generator; insecure for passwords, tokens, or security keys.secrets: Uses operating system entropy (/dev/urandom); secure for cryptography.import random
import secrets
import string
from typing import List
def generate_secure_api_key(length: int = 32) -> str:
"""Generate a cryptographically secure URL-safe API token using secrets."""
return secrets.token_urlsafe(length)
def simulation_demo() -> None:
# Reproducible pseudo-random sequence with seed
random.seed(42)
sample_list: List[str] = ["red", "blue", "green", "yellow"]
selected_item = random.choice(sample_list)
shuffled = sample_list.copy()
random.shuffle(shuffled)
print("--- Simulation (random) ---")
print(f"Random Choice: {selected_item}")
print(f"Shuffled List: {shuffled}")
print("
--- Security (secrets) ---")
print("Secure Token:", generate_secure_api_key(16))
if __name__ == "__main__":
simulation_demo()
random for Passwords: The Mersenne Twister engine in random is deterministic once internal state is observed. Always use secrets for authentication tokens or security.random.seed(value) in unit tests or ML experiments to make random behaviors deterministic and testable.secrets.compare_digest(): Use secrets.compare_digest(a, b) for constant-time string comparisons to prevent timing attack vulnerabilities.Write a function generate_temp_password(length: int = 12) -> str using secrets.choice() that picks characters from letters, digits, and punctuation.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.