[Python-ideas] Python's Source of Randomness and the random.py module Redux

Andrew Barnert abarnert at yahoo.com
Fri Sep 11 00:54:36 CEST 2015

On Sep 10, 2015, at 15:46, Andrew Barnert via Python-ideas <python-ideas at python.org> wrote:
>> On Sep 10, 2015, at 07:21, Donald Stufft <donald at stufft.io> wrote:
>> Either we can change the default to a secure
>> CSPRNG and break these functions (and the people using them) which is however
>> easily fixed by changing ``import random`` to
>> ``import random; random = random.DeterministicRandom()``
> But that isn't a fix, unless all your code is in a single module. If I call random.seed in game.py and then call random.choice in aiplayer.py, I'll get different results after your fix than I did before.
> What I'd need to do instead is create a separate myrandom.py that does this and then exports all of the bound methods of random as top-level functions, and then make game.py, aiplayer.py, etc. all import myrandom as random. Which is, while not exactly hard, certainly harder, and much less obvious, than the incorrect fix that you've suggested, and it may not be immediately obvious that it's wrong until someone files a bug three versions later claiming that when he reloads a game the AI cheats and you have to track through the problem.
> That's why I suggested the set_default_instance function, which makes this problem trivial to solve in a correct way instead of in an incorrect way.

Actually, I just thought of an even simpler solution:

Add a deterministic_singleton member to random (which is just initialized to DeterministicRandom() at startup). Now, the user fix is just to change "import random" to "from random import deterministic_singleton as random".

More information about the Python-ideas mailing list