[Python-ideas] PEP 504: Using the system RNG by default

Guido van Rossum guido at python.org
Tue Sep 15 19:33:47 CEST 2015

I had to check out of the mega-threads, but I really don't like the outcome
(unless this PEP is just the first of several competing proposals).

The random module provides a useful interface – a random() function and a
large variety of derived functionality useful for statistics programming
(e.g. uniform(), choice(), bivariate(), etc.). Many of these have
significant mathematical finesse in their implementation. They are all
accessing shared state that is kept in a global variable in the module, and
that is a desirable feature (nobody wants to have to pass an extra variable
just so you can share the state of the random number generator with some
other code).

I don’t want to change this API and I don’t want to introduce deprecation
warnings – the API is fine, and the warnings will be as ineffective as the
warnings in the documentation.

I am fine with adding more secure ways of generating random numbers. But we
already have random.SystemRandom(), so there doesn’t seem to be a hurry?

How about we make one small change instead: a way to change the default
instance used by the top-level functions in the random module. Say,


This would require the global functions to use an extra level of
indirection, e.g. instead of

  random = _inst.random

we’d change that code to say

  def random():
      return _inst.random()

(and similar for all related functions). I am not worried of the cost of
the indirection (and if it turns out too expensive we can reimplement the
module in C).

Then we could implement

  def set_random_generator(instance):
      global _inst
      _inst = instance

We could also have a function random.use_secure_random() that calls
set_random_generator() with an instance of a secure random number generator
(maybe just SystemRandom()). We could rig things so that once
use_secure_random() has been called called, set_random_generator() will
throw an exception (to avoid situations where a library module attempts to
make the shared random generator insecure in a program that has declared
that it wants secure random). It would also be fine for SystemRandom (or at
least whatever is used by use_secure_random(), if SystemRandom cannot
change for backward compatibility reasons) to raise an exception when
seed(), setstate() or getstate() are called.

Of course modules are still free to use their own instances of the Random
class. But I don’t see a reason to mess with the existing interface.

--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150915/fff6fb5a/attachment.html>

More information about the Python-ideas mailing list