# \[$\] Python's two modules for random numbers

DevFeed: [\[$\] Python's two modules for random numbers](<https://devfeed.tech/articles/python-s-two-modules-for-random-numbers-65894.md>)

Original publisher: [Read original article](<https://lwn.net/Articles/1097468/>)

Author: jake

Published: 2026-10-06T15:02:09Z

Content type: article

Language: en

Sources: [LWN.net](<https://devfeed.tech/sources/lwn-net.md>)

Topics: [Python](<https://devfeed.tech/topics/python.md>), [Cryptography](<https://devfeed.tech/topics/cryptography.md>), [modules](<https://devfeed.tech/topics/modules.md>)

Tags: [2015](<https://devfeed.tech/tags/2015.md>), [2016](<https://devfeed.tech/tags/2016.md>), [algorithm](<https://devfeed.tech/tags/algorithm.md>), [cryptography](<https://devfeed.tech/tags/cryptography.md>), [modules](<https://devfeed.tech/tags/modules.md>), [numbers](<https://devfeed.tech/tags/numbers.md>), [passwords](<https://devfeed.tech/tags/passwords.md>), [python](<https://devfeed.tech/tags/python.md>), [random](<https://devfeed.tech/tags/random.md>), [secrets](<https://devfeed.tech/tags/secrets.md>), [security](<https://devfeed.tech/tags/security.md>), [tokens](<https://devfeed.tech/tags/tokens.md>)

## AI overview

Use Python's `secrets` module for passwords, tokens, and other security-sensitive randomness: its functions draw from the operating system's random-number generator and are designed to be unpredictable. Use `random` for modeling, simulation, and reproducible tests; its Mersenne Twister is fast and can produce repeatable results from a fixed seed, but its state can be reconstructed from enough output, so it is unsuitable for cryptographic use. In the cited Python 3.15.0rc2 benchmark, `secrets.randbelow(100)` was nearly seven times slower than `random.randint(0, 99)`, though the text says this is often negligible for security tasks. `secrets` has a smaller API; `random.SystemRandom` provides additional `random` utilities backed by OS randomness when needed.

## Source excerpt

Python's random and secrets modules both include utilities for obtaining random values, but only one of them is suitable for generating passwords and security tokens. For much of Python's history, random was used for passwords and tokens anyway, despite documentation that called it unsuitable for cryptography. In 2015, Python's core team debated whether to fix that misuse by making random secure by default. Instead, in 2016, Python 3.6 added a second module: secrets. The random module is still misused at times, so it is instructive to look into how the random-number modules should be used.