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

后端 未结 3 1278
面向向阳花
面向向阳花 2021-01-18 08:08

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

相关标签:
3条回答
  • 2021-01-18 08:44

    I can't think of a way to accomplish it that wouldn't be too ugly to use routinely. This is one case where the Python programmer has to be careful about datatypes without help from the language.

    Just be thankful you're not using a language where datatypes get silently coerced between string and int.

    0 讨论(0)
  • 2021-01-18 08:45

    You could define a function to do so:

    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 讨论(0)
  • 2021-01-18 08:59

    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
      
    0 讨论(0)
提交回复
热议问题