Say I want to compare 2 variables with different data types: string and int. I have tested it both in Python 2.7.3 and Python 3.2.3 and neither throws exception. The result
No, you can't. The items are just not equal, there is no error there.
Generally speaking, it is unpythonic to force your code to only accept specific types. What if you wanted to create a subclass of the int
, and have it work everywhere an int
works? The Python boolean type is a subclass of int
, for example (True
== 1, False
== 0).
If you have to have an exception, you can do one of two things:
Test for equality on their types and raise 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 for either a or b to be a subclass of the other type, you'd need to narrow that down as needed (type(a) is type(b)
to be super strict).
Try to order the types:
if not a < b and not a > b:
# ...
In Python 3, this throws an exception when comparing numerical types with sequence types (such as strings). The comparisons succeed in Python 2.
Python 3 demo:
>>> a, b = 1, '1'
>>> not a < b and not a > b
Traceback (most recent call last):
File "", line 1, in
TypeError: unorderable types: int() < str()
>>> a, b = 1, 1
>>> not a < b and not a > b
True