[New-bugs-announce] [issue27096] Ability to get random bits from random.Random (as with os.urandom)
report at bugs.python.org
Mon May 23 18:37:26 EDT 2016
New submission from Campbell Barton:
Currently, getting random bits can be done with os.urandom,
However recently I was faced with having to make a test (with reproducible behavior), so I needed to replace os.urandom with a random generator that took a seed value.
It turns out there are 3 ways (at least) to handle this, but none are really that great.
- Create a list, fill with Random.randint(0, 255), then convert to bytes with bytes.join.
- Call Random.getrandbits(), then int.to_bytes.
- Override urandom at a system level (possible on Linux ).
While these work, they are either slow (creating a list), non trivial (OS-level) or limited - Random.getrandbits hits internal limits of an int, and accidentally using the int (running repr on it for example, locks up Python), currently CPython will fail to create values above 256mb since bits is limited to INT_MAX .
In short, to keep tests running fast, and without messing about and accounting for internal limits of CPython, there isn't a convenient way to get random bits in Python.
Since bits are a primitive type and since its already supported by os.urandom, I think its reasonable the random module could support returning random bits.
If this is accepted, I can provide a patch for this, I'm just checking to know if the functionality would be accepted.
Suggest to call random.randbits(n).
components: Library (Lib)
title: Ability to get random bits from random.Random (as with os.urandom)
versions: Python 3.6
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce