I'd like to generate some alphanumeric passwords in Python. Some possible ways are:
import string
from random import sample, choice
chars = string.ascii_letters + string.digits
length = 8
''.join(sample(chars, length)) # first way
''.join(choice(chars) for i in range(length)) # second way
But I don't the first way because only unique chars are selected and you can't generate passwords where length > len(chars)
and I don't like the second way because we have an unused i
variable. Are there any other good options?
On Python 3.6+ you should use the secrets module to generate cryptographically safe passwords. Adapted from the documentation:
import secrets
import string
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in range(20)) # for a 20-character password
For more information on recipes and best practices, see this section on recipes in the Python documentation. You can also consider adding string.punctuation
.