[Python-ideas] Python's Source of Randomness and the random.py module Redux
steve at pearwood.info
Fri Sep 11 15:49:48 CEST 2015
On Thu, Sep 10, 2015 at 04:08:09PM +1000, Chris Angelico wrote:
> On Thu, Sep 10, 2015 at 11:50 AM, Andrew Barnert via Python-ideas
> <python-ideas at python.org> wrote:
> > 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.
> +1. A single function call that replaces all the methods adds a
> minuscule constant to code size, run time, etc, and it's no less
> readable than assignment to a module attribute.
Making monkey-patching the official, recommended way to choose a PRNG is
a risky solution, to put it mildly. That means that at any time, some
other module that is directly or indirectly imported might change the
random number generators you are using without your knowledge. You want
a crypto PRNG, but some module replaces it with MT. Or visa versa.
Technically, it is true that (this being Python) they can do this now,
just by assigning to the random module:
random.random = lambda: 9
but that is clearly abusive, and if you write code to do that, you're
asking for whatever trouble you get. There's no official API to screw
over other callers of the random module behind their back. You're
suggesting that we add one.
> (If anything, it makes
> it more clearly a supported operation
Which is exactly why this is a terrible idea. You're making monkey-
patching not only officially supported, but encouraged. That will not
More information about the Python-ideas