What is the secrets.choice() function in Python?

The secrets module is a comparatively new module introduced in Python 3.6. It generates cryptographically strong random numbers, which can generate security tokens, make passwords, ensure account authentication, etc.

The secrets.choice() function takes in a non-empty sequence as an argument and returns a secure, randomly-chosen element. Here the sequence can be list, tuple, or string.

Why don’t we use the random module?

Before we move on, let’s first understand why we don’t use the random module instead. The random module is not random since the generated numbers can be reproduced if the seed value is known. Therefore, the random module is not secure for cryptographic applications because the next output is predictable from earlier outputs once the seed value is known.

Therefore, to increase security in an application in terms of randomness, we use the secrets module.

Syntax

secrets.choice(sequence)

Parameter

  • sequence: the non-empty sequence from which to choose a random number.

Return value

A number from the sequence is chosen randomly and returned.

Example

Let’s look at an example. Suppose that we pass the sequence [1, 3, 5, 7] to secrets.choice().

The function will return any number out of the given list as an output.

Let’s now take a real-world example. The secrets.choice() function can be used to generate OTP.

Code

# Importing necessary modules
import secrets
import string
# Initializing Variables
OTP = ''
digit = string.digits
# Creating 6 digit OTP
for i in range(6):
OTP +=str(''.join(secrets.choice(digit)))
print(OTP)

Explanation

  • In lines 2 and 3, we import the necessary modules.

  • In line 6, we initialize the OTP variable as an empty string.

  • In line 7, we assign the variable digit with string.digits i.e. 0123456789.

  • From lines 10 to 13, we create the OTP value by using the random digits from the secret.choice() function and then print the same.

Note that the output varies every time we run the code.

This is how we use the secrets.choice() function and create a proper random sequence, thereby enhancing the security.

Free Resources