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

Andrew Barnert abarnert at yahoo.com
Thu Sep 10 10:17:11 CEST 2015


On Sep 9, 2015, at 23:08, Chris Angelico <rosuav at gmail.com> 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. (If anything, it makes
> it more clearly a supported operation - I've seen novices not realize
> that "module.xyz = foo" is valid, but nobody would misunderstand the
> validity of a function call.)

I was only half-serious about this, but now I think I like it: it provides exactly the fix people are hoping to fix by deprecating the top-level functions, but with less risk, less user code churn, a smaller patch, and a much easier fix for novice users. (And it's much better than my earlier suggestion, too.)

See https://gist.github.com/abarnert/e0fced7569e7d77f7464 for the patch, and a patched copy of random.py. The source comments in the patch should be enough to understand everything that's changed.

A couple things:

I'm not sure the normal deprecation path makes sense here. For a couple versions, everything continues to work (because most novices, the people we're thing to help, don't see DeprecationWarnings), and then suddenly their code breaks. Maybe making it a UserWarning makes more sense here?

I made Random a synonym for UnsafeRandom (the class that warns and then passes through to DeterministicRandom). But is that really necessary? Someone who's explicitly using an instance of class Random rather than the top-level functions probably isn't someone who needs this warning, right?

Also, if this is the way we'd want to go, the docs change would be a lot more substantial than the code change. I think the docs should be organized around choosing a random generator and using its methods, and only then mention set_default_instance as being useful for porting old code (and for making it easy for multiple modules to share a single generator, but that shouldn't be a common need for novices).


More information about the Python-ideas mailing list