This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ideasman42
Recipients ideasman42
Date 2016-05-23.22:37:26
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1464043046.76.0.140037772611.issue27096@psf.upfronthosting.co.za>
In-reply-to
Content
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 [0]).

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 [1].

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).

----

[0]: http://stackoverflow.com/questions/26053875/bypass-dev-urandomrandom-for-testing
[1]: http://bugs.python.org/issue27072
History
Date User Action Args
2016-05-23 22:37:26ideasman42setrecipients: + ideasman42
2016-05-23 22:37:26ideasman42setmessageid: <1464043046.76.0.140037772611.issue27096@psf.upfronthosting.co.za>
2016-05-23 22:37:26ideasman42linkissue27096 messages
2016-05-23 22:37:26ideasman42create