Difference between Python and SageMath: operator ^ does not work for sets
In standard Python, the operator ^ is overloaded for set objects and performs the symmetric difference:
{1, 2, 3} ^ {3, 4, 5} # returns {1, 2, 4, 5} However, in SageMath, the same expression raises an error:
A = {1, 2, 3}
B = {3, 4, 5}
def test():
print("hello")
C = A ^ B
return C
test()
Result:
hello TypeError: unsupported operand type(s) for ** or pow(): 'set' and 'set' This is surprising because:
the traceback shows ** instead of ^, the error message refers to exponentiation (pow), the line number corresponds to the correct location, but the operator displayed is not the one written in the code. This suggests that SageMath does not overload ^ for sets (unlike Python), and internally treats ^ as the exponentiation operator, even when applied to sets. The resulting error message is therefore misleading.
Workaround Use the explicit symmetric difference:
A.symmetric_difference(B)
or implement XOR manually:
def xorF(s0, s1):
return (s0 - s1) | (s1 - s0)
Question Is this behavior intentional in SageMath? Should SageMath overload ^ for sets as Python does, or at least provide a clearer error message?