Python bytes() is a built-in function which returns a bytes object that is an immutable sequence of integers in the range 0 <= x < 256. Depending on the type of object passed as the source, it initializes the byte object accordingly.
Let’s look at how we can use this function in this article.
Syntax
This takes in three optional parameters, namely the:
source
-> The source which initializes the byte arrayencoding
-> The encoding of thesource
string (can be UTF-8, etc).errors
-> The behavior of the function when encoding the source string fails.
byte_array = bytes(source, encoding, errors)
Since all three arguments are optional, we can pass an empty string to generate an empty byte array (Byte array of size 0).
Depending on the type of the source
parameter, an appropriate byte array will be initialized.
- If
source
is a String, Python bytes() will convert the string to bytes usingstr.encode()
. Therefore, we must also provide the encoding and optionally errors, asencode()
is being used to process the string. - If
source
is an Integer, Python bytes() will creates an array of provided integer size, all initialized to NULL. - If
source
is of classObject
, a read-only buffer of the object will be used to initialize the byte array. - If
source
is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
If source
is None
, this will give a TypeError
, as it cannot convert a None
object to a byte array.
To understand the function better, let’s look at some examples.
Using Python bytes()
With no and None arguments
b = bytes()
print(b)
c = bytes(None)
print(c)
Output
b''
TypeError: cannot convert 'NoneType' object to bytes
With a source String
Any string provided without the encoding will raise a TypeError
.
Similarly, trying to modify the bytes
object will also give the same exception, since it is immutable by nature.
try:
a = bytes('Hello from AskPython')
except TypeError:
print('We need to specify string encoding always!')
b = bytes('Hello from AskPython', 'UTF-8')
print(type(b), b)
try:
b[0] = 10
except TypeError:
print('byte objects are immutable!')
Output
We need to specify string encoding always!
<class 'bytes'> b'Hello from AskPython'
byte objects are immutable!
With a source Integer
An integer zero-initializes that many byte element objects in the array.
a = bytes(10)
print(type(a), a)
Output
<class 'bytes'> b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
As you can see, the bytes object is a Zero initialized array consisting of 10 elements.
With a source iterable
This initializes the array with len(iterable)
number of elements, each having a value equal to the corresponding element on the iterable.
Byte array values can be accessed through normal iteration, but cannot be modified since they are immutable.
a = bytes([1, 2, 3])
print(type(a), a)
print('Length =', len(a))
# To access the byte array values, we can iterate through it!
for byte_obj in a:
print(byte_object)
Output
<class 'bytes'> b'\x01\x02\x03'
Length = 3
1
2
3
Anything else on the iterable will result in a TypeError
>>> a = bytes([1, 2, 3, 'Hi'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
Conclusion
In this article, we learned about Python bytes() function, which can convert suitable objects to a byte array.
References
- JournalDev article on bytes()