Python __bytes__() Magic Method

Rate this post

Syntax

object.__bytes__(self)

The Python __bytes__() method implements the built-in bytes() function. So, when you cal bytes(x), Python attempts to call x.__bytes__(). If the return value is not a Bytes object or the x.__bytes__() method is not defined for an object on which you call bytes(x), Python will raise a TypeError.

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Background bytes()

Python’s built-in bytes(x) function creates an immutable bytes object initialized as defined in the function argument x.

A bytes object is like a string but it uses only byte characters consisting of a sequence of 8-bit integers in the range 0<=x<256.

The returned byte object is immutable—you cannot change it after creation. If you plan to change the contents, use the bytearray() method to create a mutable bytearray object.

To understand this operation in detail, feel free to read over our tutorial or watch the following video:

Example Custom __bytes__()

In the following example, you create a custom class Data and overwrite the __bytes__() magic method so that it returns a Bytes object b'42' when trying to call bytes(x) on a custom Data object.

class Data:
    def __bytes__(self):
        return b'42'


x = Data()
res = bytes(x)

print(res)
# ... b'42' ...

TypeError: cannot convert ‘…’ object to bytes

If you hadn’t defined the __bytes__() method, Python would’ve raised a TypeError:

class Data:
    pass


x = Data()
res = bytes(x)

print(res)

Output:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 6, in <module>
    res = bytes(x)
TypeError: cannot convert 'Data' object to bytes

To fix this error, define the x.__bytes__() method for an object x before calling the built-in bytes(x) method passing this object as an argument:

class Data:
    def __bytes__(self):
        return b'42'


x = Data()
res = bytes(x)

print(res)
# ... b'42' ...

TypeError: __bool__ should return bool, returned …

Consider the following code snippet where you try to return an integer, i.e., non-bytes object in the dunder method __bytes__():

class Data:
    def __bytes__(self):
        return 42


x = Data()
res = bytes(x)

print(res)

Running this leads to the following error message on my computer:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 7, in <module>
    res = bytes(x)
TypeError: __bytes__ returned non-bytes (type int)

The reason for the TypeError: __bytes__ returned non-bytes (type ...) error is that the __bytes__() method must return a Bytes object. So, to resolve the error, return a Bytes object, for example, by using the syntax b'...' in your method definition as shown previously:

class Data:
    def __bytes__(self):
        return b'42'


x = Data()
res = bytes(x)

print(res)
# ... b'42' ...

References:

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!