Developer Documentation
Python
Updated September 19, 2026

Generate Secure Passwords in Python

Generate cryptographically secure random passwords without modulo bias in Python.

A password generator should draw randomness from the operating system or platform CSPRNG. Do not use predictable pseudo-random functions intended for simulations or UI effects.

Quick Start#

The following example uses the standard Python API or a widely used package for this task.

Quick start#

Python
1import secrets2import string34alphabet = string.ascii_letters + string.digits + "!@#$%"5password = "".join(secrets.choice(alphabet) for _ in range())6print(password)

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Memorable token#

Python
1# For URL-safe machine tokens, secrets has a direct helper:2token = secrets.token_urlsafe()3print(token)

Important Notes#

secrets is designed for security-sensitive randomness. Do not use the random module for passwords, tokens, or reset codes.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Password in other languages: