[New-bugs-announce] [issue40286] Add getrandbytes() method to random.Random

STINNER Victor report at bugs.python.org
Tue Apr 14 18:30:18 EDT 2020


New submission from STINNER Victor <vstinner at python.org>:

The random module lacks a getrandbytes() method which leads developers to be creative how to generate bytes:
https://stackoverflow.com/questions/5495492/random-byte-string-in-python

It's a common use request:

* bpo-13396 in 2011
* bpo-27096 in 2016
* https://bugs.python.org/issue40282#msg366444 in 2020

Python already has three functions to generate random bytes:

* os.getrandom(): specific to Linux, not portable
* os.urandom()
* secrets.token_bytes()

These 3 functions are based on system entropy and they block on Linux until the kernel collected enough entropy: PEP 524.

While many users are fine with these functions, there are also use cases for simulation where the security doesn't matter, and it's more about being able to get reproducible experience from a seed. That's what random.Random is about.

The numpy module provides numpy.random.bytes(length) function for such use case:
https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.bytes.html

One example can be to generate UUID4 with the ability to reproduce the random UUID from a seed for testing purpose, or to get reproducible behavior.

Attached PR implements the getrandbytes() method.

----------
components: Library (Lib)
messages: 366454
nosy: vstinner
priority: normal
severity: normal
status: open
title: Add getrandbytes() method to random.Random
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue40286>
_______________________________________


More information about the New-bugs-announce mailing list