[New-bugs-announce] [issue27096] Ability to get random bits from random.Random (as with os.urandom)

Campbell Barton 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 [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

components: Library (Lib)
messages: 266202
nosy: ideasman42
priority: normal
severity: normal
status: open
title: Ability to get random bits from random.Random (as with os.urandom)
type: enhancement
versions: Python 3.6

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list