## Syntax

object.__xor__(self, other)

The Python `__xor__()`

method implements the built-in Bitwise XOR ^ operation. So, when you cal `x ^ y`

, Python attempts to call `x.__xor__(y)`

. If the method is not implemented, Python first attempts to call `__rxor__`

on the right operand and if this isn’t implemented either, it raises 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 Bitwise XOR ^

Python’s bitwise XOR operator performs *logical XOR* on each bit position on the binary representations of integers `x`

and `y`

.

Each output bit evaluates to 1 *if and only if *exactly one of the two input bits at the same position are 1.

For example, the integer expression `4 ^ 3`

is translated to the binary operation `0100 ^ 0011`

which results in `0111`

because for the last three positions exactly one bit is 1.

In this example, you apply the ** bitwise XOR **operator to two integers 32 and 16:

>>> 32 ^ 16 48

The expression `32 ^ 16`

operates on the bit representations `"0100000"`

(decimal 32) and `"0010000"`

(decimal 16) and performs ** bitwise XOR** resulting in binary

`"0110000"`

(decimal 48):First Operand `x` | 1 | 0 | 0 | 0 | 0 | 0 |

Second Operand `y` | 0 | 1 | 0 | 0 | 0 | 0 |

`x ^ y` | 1 | 1 | 0 | 0 | 0 | 0 |

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

## Example Custom __xor__()

In the following example, you create a custom class `Data`

and overwrite the `__xor__()`

magic method so that it returns a dummy string when trying to calculate the bitwise XOR operation.

class Data: def __xor__(self, other): return '... my result of XOR ...' a = Data() b = Data() print(a ^ b) # ... my result of XOR ...

If you hadn’t defined the `__xor__()`

method, Python would’ve raised a `TypeError`

.

## TypeError: unsupported operand type(s) for ^

Consider the following code snippet where you try to calculate the bitwise XOR operation on custom objects without defining the dunder method `__xor__()`

:

class Data: pass a = Data() b = Data() print(a ^ b)

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

Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 8, in <module> print(a ^ b) TypeError: unsupported operand type(s) for ^: 'Data' and 'Data'

The reason for this error is that the `__xor__()`

method has never been defined—and it is not defined for a custom object by default. So, to resolve the `TypeError: unsupported operand type(s) for ^`

, you need to provide the `__xor__(self, other)`

method in your class definition as shown previously:

class Data: def __xor__(self, other): return '... my result of XOR ...'

Of course, you’d use another return value in practice as explained in the **“Background”** section.

## Python __xor__ vs __rxor__

Say, you want to calculate the `^`

operation on two custom objects `x`

and `y`

:

print(x ^ y)

Python first tries to call the left object’s `__xor__()`

method `x.__xor__(y)`

. But this may fail for two reasons:

- The method
`x.__xor__()`

is not implemented in the first place, or - The method
`x.__x`

is implemented but returns a`or`

__()`NotImplemented`

value indicating that the data types are incompatible.

If this fails, Python tries to fix it by calling the `y.__rxor__()`

for *reverse bitwise XOR *on the right operand `y`

.

If the reverse bitwise XOR method is implemented, Python knows that it doesn’t run into a potential problem of a non-commutative operation. If it would just execute `y.__xor__(x)`

instead of `x.__xor__(y)`

, the result would be wrong because the operation may be non-commutative when defined as a custom operation. That’s why `y.__rxor__(x)`

is needed.

So, the difference between `x.__xor__(y)`

and `x.__rxor__(y)`

is that the former calculates `x ^ y`

whereas the latter calculates `y ^ x`

— both calling the respective method defined on the object `x`

.

You can see this in effect here where we attempt to call the operation on the left operand `x`

—but as it’s not implemented, Python simply calls the reverse operation on the right operand `y`

.

class Data_1: pass class Data_2: def __rxor__(self, other): return 'called reverse bitwise XOR' x = Data_1() y = Data_2() print(x ^ y) # called reverse bitwise XOR

**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.

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.