How to use Python `secret` module to generate random integer?

The secret module provides the same interface as random; the underlying random generator has just been changed to SystemRandom which is cryptographically strong.

In short, use it as you would random in circumstances that require a bit more security; I doubt choice suffers from performance so much to warrant your concern.


secrets.choice(range(n, m)) should be fine, since range is lazy on Python 3.

n + secrets.randbelow(m-n) is another option. I wouldn't use it, since it's less obviously correct.

Since secrets provides access to the SystemRandom class, with the same interface as random.Random, you can also keep your own SystemRandom instance:

my_secure_rng = secrets.SystemRandom()

and do

my_secure_rng.randrange(n, m)