Python Glossary Русский

Python 3.6+secretsfunction

secrets.choice()

random numbers

Chooses one random element from a non-empty sequence using a cryptographically strong source.

Syntax

secrets.choice(seq)

It has the same interface as random.choice, but there is no seed and the result cannot be predicted. For passwords pick characters in a loop: ''.join(secrets.choice(alphabet) for _ in range(n)). An empty sequence raises IndexError and a set raises TypeError because it is not indexable.

Examples

import secrets, string
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for _ in range(12))
print(len(password))  # → 12
print(password)  # → ? случайный пароль
import secrets
try:
    secrets.choice([])
except IndexError as e:
    print(type(e).__name__)  # → IndexError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy