Python Glossary Русский

Python 3.9+randomfunction

random.randbytes

bits and bytes

Returns n random bytes (Python 3.9+); reproducible under a seed — fine for tests, but not for tokens or salts.

Syntax

random.randbytes(n)

Its real edge over os.urandom is repeatability: fix the seed and the same byte string comes back, which makes binary test fixtures deterministic. For salts, session tokens or anything else that guards access, reach for secrets.token_bytes() — this generator becomes predictable once enough of its output is seen.

Examples

import random
print(len(random.randbytes(4)))   # → 4
print(type(random.randbytes(2)))   # → <class 'bytes'>
print(random.randbytes(0))   # → b''
print(len(random.randbytes(16).hex()))   # → 32
print(random.randbytes(-1))   # → ValueError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy