[issue40346] Add random.BaseRandom to ease implementation of subclasses

Raymond Hettinger report at bugs.python.org
Fri Apr 24 20:55:03 EDT 2020


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

SystemRandom is a weird special case.  Otherwise, almost every PRNG is going to need seed(), getstate(), and setstate().  A base class should each offer some reusable code to minimize the burden on the subclass:

* The existing seed method allows multiple input types to be collapsed to a long integer.  A subclass can extend this as needed or can override it completely.  This is useful and will tend to give a more consistent API across multiple RNGs.

* The getstate/setstate methods take care of the gauss_next value and allow the seeding to be versioned.  This is also useful and helps us insulate users from state related implementation details such as gauss_next.

Please don't lose the above functionality by default.

Also, please make sure that code written to the existing spec continues to work.¹

+1 on offering a PCG generator; however, it should an additional alternative to MT and SystemRandom rather than a replacement.  Also, it needs to work well on 32-bit builds.  Notes should be added that its state space is *much* smaller than MT, so shuffle() becomes state space limited at much smaller population sizes -- meaning that a large number of possible permutations become unreachable by shuffle() -- for example, to cover all possible shuffles for a deck of 52 playing cards requires 226 bits.²  Also, I expect that PCG won't offer us the same performance advantage as it does for numpy because the MT code itself is only a fraction of the time in a call to random(); the rest of the time is in the function call overhead, converting the bytes to a C double, and creating a new Python float object.

I would still like to see a PEP for this. 


¹ https://code.activestate.com/recipes/576707/
² factorial(52).bit_length()

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40346>
_______________________________________


More information about the Python-bugs-list mailing list