[Python-ideas] Globally configurable random number generation

Andrew Barnert abarnert at yahoo.com
Tue Sep 15 01:10:19 CEST 2015

On Sep 14, 2015, at 06:32, Nick Coghlan <ncoghlan at gmail.com> wrote:
> This is an expansion of the random module enhancement idea I
> previously posted to Donald's thread:
> https://mail.python.org/pipermail/python-ideas/2015-September/035969.html

Since I suggested the set_default_instance and the singleton instances that can be imported in place of the module, I'm obviously happy with those parts.

However, I think you still haven't solved the problem with my proposal that you set out to solve.

The main difference is that I wanted to deprecate (and eventually make it an error) to use the top-level functions without calling set_default_instance, while you want to allow them and gradually shift the semantics from using the seeded to the seedless PRNG.

As I understand it, the reason for this is that you want to make it possible for someone to write "from random import choice", and not get a warning or error telling them they need to call set_default_instance or import one of the singletons instead.

But then you're encouraging people to write code that's broken in 3.6 and earlier--and that's also potentially broken in 3.7 if used together with any code that calls set_default_instance (because that can't retroactive fix anything from-imported before the call). So, it takes 18 more months to provide any benefit, and it adds an extra cost.

Maybe the suggestion of not allowing set_default_instance to be called more than once and/or after any other functions is sufficient, but I'm not sure that it is.

What about this change: replace the three singleton instances with three modules, so we can tell people (and 2to3 and similar mechanical tools) to replace "from random import choice" with "from random.seedless_random import choice"? Would that be acceptable for novices? (And, If so, would that mean we no longer need the set_default_instance and can just flat-out deprecate the top-level functions in random?)

If that's not sufficient because the name is too long/too nested, could we just flatten the names out, so it's "from seedless_random import choice", and then the deprecation process is just making random an alias for seeded_random and then switching it to seedless_random later? (I don't think there's any official cross-platform way to alias modules like that, and having to do some ugly sys.modules munging to force them to be the same instance, or using a special module finder just for this case, etc. is obviously ugly, but it may be worth doing anyway.) One nice advantage of this is that it's dead-easy to backport; if I need seeded_random, I can write code that works for 2.6+/3.3+ by just spending on seeded_random from PyPI...

More information about the Python-ideas mailing list