Did you know?
Python's random module is not safe for passwords; use secrets instead.
Swap random.choice() for secrets.choice() in any code that makes passwords, tokens or keys.
- Programming
- Last checked
Explained
Python’s random module uses the Mersenne Twister generator. It is fast and fine for games, simulations and sampling, but it is predictable: once someone has seen 624 consecutive 32-bit outputs, they can rebuild its internal state and predict every value that follows. The Python documentation warns not to use it for security.
For passwords, API keys, reset links and session tokens, use the secrets module (Python 3.6+). It reads from the operating system’s cryptographically secure source, os.urandom(). In most code the fix is one word:
import secrets, string
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for _ in range(16))For tokens you don’t even need an alphabet: secrets.token_urlsafe(16) returns about 22 URL-safe characters from 16 random bytes. If you need a secure shuffle() or sample(), use secrets.SystemRandom(), which has the same methods as random.
Keep random for non-security work, where its ability to repeat a sequence with random.seed() is useful.
Learn more
- How to Generate a Secure Random Password in Python Full guide · Updated Nov 2026
