astrojuanlu astrojuanlu - 2 months ago 4
Python Question

Converting int to bytes in Python 3

I was trying to build this bytes object in Python 3:


so I tried the obvious (for me), and found a weird behaviour:

>>> bytes(3) + b'\r\n'


>>> bytes(10)

I've been unable to see any pointers on why the bytes conversion works this way reading the documentation. However, I did find some surprise messages in this Python issue about adding
to bytes (see also Python 3 bytes formatting):

This interacts even more poorly with oddities like bytes(int) returning zeroes now


It would be much more convenient for me if bytes(int) returned the ASCIIfication of that int; but honestly, even an error would be better than this behavior. (If I wanted this behavior - which I never have - I'd rather it be a classmethod, invoked like "bytes.zeroes(n)".)

Can someone explain me where the heck does this behaviour come from?


That's the way it was designed - and it makes sense because usually, you would call bytes on an iterable instead of a single integer:

>>> bytes([3])

The docs state this, as well as the docstring for bytes:

 >>> help(bytes)
 bytes(int) -> bytes object of size given by the parameter initialized with null bytes