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 of comparison is False. Can I configure or run Python with different options to throw exception in this case?
ks@ks-P35-DS3P:~$ python2
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a="123"
>>> b=123
>>> a==b
False
>>>
ks@ks-P35-DS3P:~$ python3
Python 3.2.3 (default, Apr 12 2012, 19:08:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a="123"
>>> b=123
>>> a==b
False
>>>
ks@ks-P35-DS3P:~$
解决方案
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