Is it possible to throw a Python exception when comparing different data types equally?

Let's say I want to compare 2 variables with different data types: string and int. I tested it in both Python 2.7.3 and Python 3.2.3, and none of them raise an exception. The result of the comparison is False . Can I configure or run Python with various parameters to throw exceptions 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 :~$ 
+4
source share
3 answers

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 
+5
source

I can't figure out how to do this, which would not be too ugly for normal use. This is one case where a Python programmer has to be careful about data types without the help of a language.

Just thank you for not using a language where datatypes are silently forced between a string and an int.

+1
source

You can define a function for this:

 def isEqual(a, b): if not isinstance(a, type(b)): raise TypeError('a and b must be of same type') return a == b # only executed if an error is not raised 
0
source

All Articles