Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make Python throw exception when equal comparing different data types?

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:~$ 
like image 214
ks1322 Avatar asked Mar 16 '13 16:03

ks1322


People also ask

How do you compare data types in Python?

Python has a built-in function called instance() that compares the value with the type given. It the value and type given matches it will return true otherwise false. Using isinstance(), you can test for string, float, int, list, tuple, dict, set, class, etc.

Why is it important to handle Python 3 exceptions?

Exception handling allows you to separate error-handling code from normal code. An exception is a Python object which represents an error. As with code comments, exceptions helps you to remind yourself of what the program expects. It clarifies the code and enhances readability.

Can you throw exceptions in Python?

Sometimes you want Python to throw a custom exception for error handling. You can do this by checking a condition and raising the exception, if the condition is True. The raised exception typically warns the user or the calling application.


1 Answers

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:

  1. 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).

  2. 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 "<stdin>", line 1, in <module>
    TypeError: unorderable types: int() < str()
    >>> a, b = 1, 1
    >>> not a < b and not a > b
    True
    
like image 183
Martijn Pieters Avatar answered Oct 02 '22 19:10

Martijn Pieters