No, you canβt. Elements are simply not equal, there are no errors.
Generally speaking, it is not surprising to force your code to accept only certain types. What if you want to subclass int and make it work wherever int works? The Boolean type of Python is a subclass of int , for example ( True == 1, False == 0).
If you have an exception, you can do one of two things:
Check the equality of their types and create an exception yourself:
if not isinstance(a, type(b)) and not isinstance(b, type(a)): raise TypeError('Not the same type') if a == b:
This example allows either a or b to be a subclass of another type, you need to narrow it down as needed ( type(a) is type(b) will be strictly strict).
Try sorting the types:
if not a < b and not a > b:
In Python 3, this throws an exception when comparing numeric types with sequence types (e.g. strings). The comparison is done in Python 2.
Python 3 demo:
>>> a, b = 1, '1' >>> not a < b and not a > b Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: int() < str() >>> a, b = 1, 1 >>> not a < b and not a > b True
source share