In Python 3.6, new module, secrets
, was added.
What is the most efficient way to generate random integer in range [n, m)
using this module?
I tried choice(range(n, m))
, but I doubt it is the best way.
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)