To increase randomness, make use of random.SystemRandom()
:
The following happens: the most visited part of the official documentation shows "chargeable" that look like functions, in the module random
- do
import random
a = random.randint(...)
b = random.choice(...)
But these "functions" are actually methods of a class
random.Random
that are exposed directly in the module for ease of use.
So if you create an instance of random.Random
- will have as methods these same calls - randint, randrange, Choice, etc...
and a seed
. Only that the module random
has also the specialized class
SystemRandom
that uses as source of the random numbers the operating system API for this. That is, in Linux takes values from /dev/random
, in Windows uses CryptGenRandom
, etc... These random numbers of the system are, as far as possible, guaranteed random enough for use in crypto tasks, etc... and far beyond the pseudo-random ones that the random.Random
normal provides.
So just create an instance of SystemRandom
and call the methods of that instance instead of the normal functions of the module Random:
from random import SystemRandom
random = SystemRandom ()
a = random.randint(...)
b = random.choice(...)
As to the seed
, on objects SystemRandom
the function seed
exists, by virtue of the object orientation model, in which specialized classes have to expose the methods and attributes of parents, but in fact, it is not used - it is even in the documentation of it: Stub method. Not used for a system random number generator.
The random data source used by SystemRandom
is exposed in the module os
and can also be used directly with the call os.urandom(n)
- and returns a byte sequence with the values provided by the operating system. The SystemRandom
encapsulates this call and already makes available all the practical methods we know - randint, Choice, Uniform, etc...
Possible duplicate of How computer randomization is generated?
– hkotsubo
The doubt needs to always use Random.Seed() before calling Random.Random() or not? The Python function Random.Random() of the library already generates a Seed internally?
– Thiago Krempser
Random already generates a Seed, you can set a manually Seed, this is useful to test some procedures, because you already know the numbers generated can predict the behavior and "debug" correctly.
– Augusto A