bpo-40346: Random subclass randbytes uses getrandbits#19700
bpo-40346: Random subclass randbytes uses getrandbits#19700vstinner wants to merge 7 commits intopython:masterfrom vstinner:randbytes_subclass
Conversation
|
I didn't change the documentation. Or do you think that it must be said explicitly that Random subclass implement randbytes() with getrandbits()? My minor documentation issue is that SystemRandom subclasses don't get a randbytes() implementation which uses getrandbits(): SystemRandom subclasses get SystemRandom.randbytes() which calls os.urandom(). |
Subclasses of the random.Random and random.SystemRandom classes now get a randbytes() method implementation which uses the getrandbits() method.
Oh, I found a project in the wild which creates a SystemRandom subclass: So I modified my PR to change also SystemRandom subclasses, and I completed the documentation. |
|
I updated the PR to address @serhiy-storchaka's comments and I added more tests on two other kinds of subclasses. |
|
I am not sure that pickling the |
super.__init_subclass__ => super().__init_subclass__ Cleanup also tests.
Check SystemRandom.getrandbits, not _random.Random.getrandbits.
pickle can be used to serialize/deserialize instances. Example: Output: Two MyRandom instances are created, but MyRandom.randbytes is only set once by Random.__init_subclass(MyRandom): when the class is created. |
|
I meant pickling the method. pickle.dumps(MyRandom.randbytes) |
Alright, that's broken because you asked me to ensure that Output: |
|
I think we can have this cake and eat it. Define |
Which second option? Remove the C implementation and always implement randbytes() using getrandbits() in Lib/random.py? Well, I proposed a solution to keep the optimization (C implementation) and don't require subclasses to have to override a 6th method (randbytes). I'm not super excited by adding more special cases I let @rhettinger and you decide which approach is the best. When I read https://bugs.python.org/issue40346 it's not even clear if we support subclassing or not, nor if performance matters or not. I'm now very confused :-( Now at least, we have multiple choices, and I let you decide which one is the best ;-) |
|
The second option which I mentioned in my comment #19700 (comment) and repeated in #19700 (comment). |
Well, it seems like there are different ways to implement this change. But I'm not sure that this approach is the best. For now, I will leave the PR as it is. I'm now waiting for a feedback on https://bugs.python.org/issue40346#msg367202 |
|
I abandon my BaseRandom PR #19631 and this PR since there is no clear consensus on these changes: see https://bugs.python.org/issue40346 I wrote PR #19797 instead: "Remove C implementation of Random.randbytes()". |
Subclass of the random.Random class now get a randbytes() method
implementation which uses the getrandbits() method.
https://bugs.python.org/issue40346