I ran across the caret operator in python today and trying it out, I got the following output:
>>> 8^3
11
>>> 8^4
12
>>> 8^1
9
>
Generally speaking, the symbol ^ is an infix version of the __xor__ or __rxor__ methods. Whatever data types are placed to the right and left of the symbol must implement this function in a compatible way. For integers, it is the common XOR operation, but for example there is not a built-in definition of the function for type float with type int:
In [12]: 3 ^ 4
Out[12]: 7
In [13]: 3.3 ^ 4
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 3.3 ^ 4
TypeError: unsupported operand type(s) for ^: 'float' and 'int'
One neat thing about Python is that you can override this behavior in a class of your own. For example, in some languages the ^ symbol means exponentiation. You could do that this way, just as one example:
class Foo(float):
def __xor__(self, other):
return self ** other
Then something like this will work, and now, for instances of Foo only, the ^ symbol will mean exponentiation.
In [16]: x = Foo(3)
In [17]: x
Out[17]: 3.0
In [18]: x ^ 4
Out[18]: 81.0