[New-bugs-announce] [issue13396] new method random.getrandbytes()

Amaury Forgeot d'Arc report at bugs.python.org
Sun Nov 13 17:43:41 CET 2011

New submission from Amaury Forgeot d'Arc <amauryfa at gmail.com>:

I noticed that several usages of random.getrandbits() actually need bytes.  A few examples:
- Lib/test/test_zlib.py calls "random.getrandbits(8 * _1M).to_bytes()"
- Twisted uses the %x format and then call .decode('hex')
Another examples found with Code Search:
- struct.pack("Q", random.getrandbits(64))
- for i in range(8): ClientChallenge+= chr(random.getrandbits(8))
- key = sha1(str(random.getrandbits(8*20))).digest()

random.getrandbits() itself is not a cheap call: it ends with a call to _PyLong_FromByteArray, and transformation to bytes will involve more copy, conversions from 30bit digits (or 15bit digits) to bytes, or worse.

This patch adds random.getrandbytes(), which creates a bytes string directly from calls to genrand_int32().

files: getrandbytes.patch
keywords: patch
messages: 147557
nosy: amaury.forgeotdarc, rhettinger
priority: normal
severity: normal
status: open
title: new method random.getrandbytes()
type: feature request
versions: Python 3.2, Python 3.3
Added file: http://bugs.python.org/file23679/getrandbytes.patch

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list