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 <rep...@bugs.python.org>
<http://bugs.python.org/issue27096>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to