Python bytes function
last modified November 29, 2026 Python 3.15
In this article we show how the bytes constructor builds an immutable byte sequence from the different kinds of input it accepts.
The type itself, its literals, its methods, and decoding are covered in Python bytes. Here the focus is the call bytes(...): which argument combinations are valid, what each one produces, and which exception appears when the input does not fit.
Text and bytes conversions with error handlers are explained in Python encode/decode, and binary file input is shown in Python read file.
An empty value or a length
With no argument the constructor returns an empty bytes object. With one integer argument it returns that many zero bytes.
print(bytes()) print(bytes(0)) print(bytes(4)) print(bytes(True)) print(len(bytes(4))) print(bytes(4)[0])
The integer is a count, not a value: bytes(4) does not produce the byte four, it produces four bytes whose value is zero. This is the fastest way to allocate a fixed-size buffer.
A negative count raises ValueError: negative count. Booleans are integers in Python, so bytes(True) is one zero byte.
$ python length_bytes.py b'' b'' b'\x00\x00\x00\x00' b'\x00' 4 0
An iterable of integers
Any iterable of integers works, as long as every value is in the range 0 to 255. Lists, tuples, generators, and range objects are common sources.
print(bytes([70, 97, 108, 99, 111, 110]))
print(bytes(range(65, 70)))
print(bytes([0, 127, 255]))
print(bytes(True for _ in range(3)))
try:
print(bytes([256]))
except ValueError as e:
print('ValueError:', e)
try:
print(bytes([-1]))
except ValueError as e:
print('ValueError:', e)
Values 32 to 126 are shown as printable ASCII characters in the representation, and everything else appears as an escape such as \x00 or \xff. The bytes themselves are always the same eight-bit values.
The range check happens while the iterable is consumed, so a generator that produces a bad value fails at that element. A list of strings fails earlier with TypeError, because a string is not an integer.
$ python iterable_bytes.py b'Falcon' b'ABCDE' b'\x00\x7f\xff' b'\x01\x01\x01' ValueError: bytes must be in range(0, 256) ValueError: bytes must be in range(0, 256)
Text with an encoding
When the first argument is a string, the second argument is mandatory and names the encoding. Without it the constructor cannot know which bytes the characters should become.
print(bytes('falcon', 'utf-8'))
print(bytes('falcon', encoding='ascii'))
print(bytes('naïve', 'utf-8'))
print('falcon'.encode('utf-8'))
print(bytes('naïve', 'ascii', 'replace'))
try:
bytes('falcon')
except TypeError as e:
print('TypeError:', e)
try:
bytes('naïve', 'ascii')
except UnicodeEncodeError as e:
print('UnicodeEncodeError:', e)
The third argument is the error handler. replace substitutes a question mark for every character that the encoding cannot represent, while the default strict raises UnicodeEncodeError.
The encode method of a string does the same work as bytes(text, encoding); it is the form most code uses. The constructor form is useful when the value may already be bytes, because bytes(b'falcon', 'utf-8') is an error and the type has to be checked before choosing a branch.
$ python string_bytes.py b'falcon' b'falcon' b'na\xc3\xafve' b'falcon' b'na?ve' TypeError: string argument without an encoding UnicodeEncodeError: 'ascii' codec can't encode character '\xef' in position 2: ordinal not in range(128)
Hexadecimal text
The class method fromhex reads pairs of hexadecimal digits. ASCII whitespace between the pairs is ignored, and upper and lower case are both accepted.
print(bytes.fromhex('48 65 6c 6c 6f'))
print(bytes.fromhex('48656C6C6F'))
print(bytes.fromhex(' 48\t65\n6c '))
print(b'Hello'.hex())
try:
bytes.fromhex('48656')
except ValueError as e:
print('ValueError:', e)
try:
bytes.fromhex('zz')
except ValueError as e:
print('ValueError:', e)
Each pair is one byte, so the odd-length string is rejected even though every character in it is a valid digit. Whitespace may sit between pairs and around the whole string, but not inside a pair.
The hex method performs the reverse conversion and always returns lower case without separators. Passing the result back to fromhex restores the original bytes.
$ python fromhex.py b'Hello' b'Hello' b'Hel' 48656c6c6f ValueError: fromhex() arg must contain an even number of hexadecimal digits ValueError: non-hexadecimal number found in fromhex() arg at position 0
Objects that expose a buffer
A bytearray, a memoryview, and an array.array all expose their memory as a buffer. The constructor copies those bytes into a new immutable object.
from array import array
mutable = bytearray(b'falcon')
view = memoryview(mutable)
numbers = array('B', [1, 2, 3])
frozen = bytes(mutable)
mutable[0] = ord('F')
print(frozen)
print(bytes(view))
print(bytes(numbers))
print(memoryview(mutable).readonly)
print(memoryview(frozen).readonly)
The copy is made when the constructor runs: changing mutable afterwards does not change frozen. This is what makes bytes safe to share between threads and to use as a dictionary key.
memoryview itself does not copy; it only gives access to the existing memory. The last two lines show the difference: a view of the bytearray can be written through, while a view of the bytes object reports readonly as True.
$ python buffer_bytes.py b'falcon' b'Falcon' b'\x01\x02\x03' False True
The __bytes__ method
For any other object the constructor looks for a __bytes__ method and returns what that method returns. The result must be a bytes object, not a string or a bytearray.
class Callsign:
def __init__(self, code):
self.code = code
def __bytes__(self):
return self.code.encode('ascii')
print(bytes(Callsign('FLC')))
print(Callsign('FLC').__bytes__())
try:
bytes(3.5)
except TypeError as e:
print('TypeError:', e)
try:
bytes(object())
except TypeError as e:
print('TypeError:', e)
The method receives no arguments and does the encoding itself, so the class decides which encoding its bytes use. The constructor only validates the returned type.
Numbers other than integers and objects without the method raise TypeError. The message names the type that could not be converted, which is usually enough to find the offending value.
$ python dunder_bytes.py b'FLC' b'FLC' TypeError: cannot convert 'float' object to bytes TypeError: cannot convert 'object' object to bytes
Choosing the right form
The argument types decide the form, and some combinations are rejected even though each part is valid on its own. A quick summary with real calls makes the boundaries clear.
cases = [
(b'falcon',),
(bytearray(b'falcon'),),
('falcon', 'utf-8'),
('falcon',),
(5,),
(5, 'utf-8'),
([70, 97, 108],),
(None,),
]
for args in cases:
try:
print(args, '->', bytes(*args))
except (TypeError, ValueError) as e:
print(args, '->', type(e).__name__, e)
Each line shows which branch of the constructor was chosen. A bytes or buffer argument is copied, a string with an encoding is encoded, and an integer is treated as a length.
The last four rows are the mistakes that appear most often in practice: forgetting the encoding, passing a length together with an encoding, passing a list of characters instead of a list of integers, and passing None. The exception type and message identify the problem without any guessing.
$ python choose_form.py
(b'falcon',) -> b'falcon'
(bytearray(b'falcon'),) -> b'falcon'
('falcon', 'utf-8') -> b'falcon'
('falcon',) -> TypeError string argument without an encoding
(5,) -> b'\x00\x00\x00\x00\x00'
(5, 'utf-8') -> TypeError encoding without a string argument
([70, 97, 108],) -> b'Fal'
(None,) -> TypeError cannot convert 'NoneType' object to bytes
Source
In this article we have called the bytes constructor with lengths, iterables, text, hexadecimal strings, buffers, and custom objects, and looked at the errors each form raises. For the type as a whole, including indexing, slicing, and its methods, see Python bytes. The mutable sibling is described in Python bytearray function.
Author
List all Python tutorials.