[Python-ideas] Python's Source of Randomness and the random.py module Redux
abarnert at yahoo.com
Thu Sep 10 03:50:43 CEST 2015
On Sep 9, 2015, at 18:25, Random832 <random832 at fastmail.com> wrote:
> Andrew Barnert via Python-ideas
> <python-ideas at python.org> writes:
>> You can work around that by,
>> e.g., providing your own myrandom.py that does that and then using
>> "from myrandom import random" everywhere, or by stashing a random_inst
>> inside the random module or builtins or something and only creating it
>> if it doesn't exist, etc., but all of these are things that people
>> will rightly complain about.
> Of course, this brings to mind the fact that there's *already* an
> instance stashed inside the random module.
> At that point, you might as well just keep the module-level functions,
> and rewrite them to be able to pick up on it if you replace _inst
> (perhaps suitably renamed as it would be a public variable) with an
> instance of a different class.
The whole point is to make people using the top-level functions see a DeprecationWarning that leads them to make a choice between SystemRandom and DeterministicRandom. Just making inst public (and dynamically switchable) doesn't do that, so it doesn't solve anything.
However, it seems like there's a way to extend it to do that:
First, rename Random to DeterministicRandom. Then, add a subclass called Random that raises a DeprecationWarning whenever its methods are called. Then preinitialize inst to Random(), just as we already to. Existing code will work, but with a warning. And the text of that warning or the help it leads to or the obvious google result or whatever can just suggest "add random.inst = random.DeterministicRandom() or random.inst = random.SystemRandom() at the start of your program". That has most of the benefit of deprecating the top-level functions, without the cost of the solution being non-obvious (and the most obvious solution being wrong for some use cases).
Of course it adds the cost of making the module slower, and also more complex. Maybe a better solution would be to add a random.set_default_instance function that replaced all of the top-level functions with bound methods of the instance (just like what's already done at startup in random.py)? That's simple, and doesn't slow down anything, and it seems like it makes it more clear what you're doing than setting random.inst.
More information about the Python-ideas