This snippet generates strong, randomized passwords with customizable complexity options (length, character types). It’s useful for creating secure credentials for applications, user accounts, or API keys.
import secrets
import string
def generate_password(length=16, use_uppercase=True, use_digits=True, use_special=True):
"""Generate a secure random password with specified complexity."""
characters = string.ascii_lowercase
if use_uppercase:
characters += string.ascii_uppercase
if use_digits:
characters += string.digits
if use_special:
characters += string.punctuation
if not characters:
raise ValueError("At least one character type must be selected")
return ''.join(secrets.choice(characters) for _ in range(length))
# Example usage
print("Standard password:", generate_password())
print("Numeric PIN:", generate_password(6, use_uppercase=False, use_special=False))
print("Extra strong:", generate_password(24, use_uppercase=True, use_digits=True, use_special=True))
secrets module (cryptographically secure) instead of randomgenerate_password() with no arguments for a 16-character password with all character typeslength: Set password length (default 16)use_uppercase: Include A-Z (default True)use_digits: Include 0-9 (default True)use_special: Include !@#$% etc. (default True)Standard password: gH7#kL9@mN2!pQ4%
Numeric PIN: 729384
Extra strong: Wb3$kP8#mN1@xZ6*qL9%vR4^cT7&yU2
For production use, consider adding these features: