DEV Community

Cover image for Generate random bytes of size n in Python 3.9
Izaan Zubair
Izaan Zubair

Posted on

Generate random bytes of size n in Python 3.9

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
Enter fullscreen mode Exit fullscreen mode

Alt text of image

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'>
Enter fullscreen mode Exit fullscreen mode

The randbytes() shouldn't be used as a substitute for generating secret tokens as Python's official documentation advises against it

Top comments (0)