Generating random bytes was somewhat complicated in Python before the new version 3.9 finally introduced the randbytes()
function.
Prior, we could rely on functions such as os.getrandom()
, os.urandom()
or secrets.token_bytes()
but couldn't generate pseudo-random patterns.
Python version 3.9 introduced the new function, randbytes(n) which returns bytes of size "n". Let's take a look at how the function works!
In order to use the function, we have to import it from the random module.
Let's try generating pseudo-random bytes of size 2:
from random import randbytes
random_bytes = randombytes(2)
random_bytes
>>> b'\xf29' # Output
For the inexperienced, it may look like that the returned object is of type/class str, but it isn't.
type(random_bytes)
>>> <class 'bytes'>
The randbytes() shouldn't be used as a substitute for generating secret tokens as Python's official documentation advises against it
Top comments (0)