当比较不同的数据类型时,我能否让Python抛出异常?

10

假设我想比较两个不同数据类型的变量:字符串和整数。我在Python 2.7.3和Python 3.2.3中都进行了测试,都没有抛出异常。比较的结果是False。我能否配置或运行Python以在这种情况下引发异常?

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
你想要为所有对象重载__eq__吗? - BlackVegetable
1
你实际上想要做什么? - Burhan Khalid
@Burhan Khalid: 我想要保护自己免受不相关类型的意外比较,并尽早了解它。 - ks1322
@Jesse Rusak:我的意思是这些变量在某种意义上是相等的,如果将a显式地转换为整数,则它们将相等。但实际上,由于数据类型不同,它们并不相等。 - ks1322
3
避免此类意外的最佳方式是编写单元测试。 - John La Rooy
显示剩余2条评论
3个回答

8
不行,它们的项目不相等,没有错误。一般来说,强制代码只接受特定类型是不符合Python风格的。如果你想创建一个int子类,并使其在任何int工作的地方都能正常工作,那该怎么办呢?例如,Python布尔类型是int的一个子类(True == 1,False == 0)。如果你必须要有一个异常,你可以做以下两件事情之一:
  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
    

@BlackVegetable 是的,但是如果你检查两个方向,那么如果任何一个失败了(即两个类型必须完全相同),你会抛出异常吗?还是两个都失败了(即你还允许一个类型是另一个子类型)?这是关于此检查性质的关键点。 - Jesse Rusak
好的观点。这是只有原帖作者能为我们回答的问题,我相信他有具体的要求。 - BlackVegetable
很奇怪的是,Python3在进行<比较时会抛出异常,但在进行==比较时却不会。 - ks1322
@ks1322:完全不行。你不能排序不同类型(应该是1在foobar之前还是之后?),但你可以确定它们不相等。 - Martijn Pieters
但是有很多情况下类是可比较的,但不可排序,对吧?选项2对我来说有点奇怪。总的来说,我个人非常喜欢 Python 实际上内置了多态性这一事实。例如,即使 Bloom 过滤器的成员无法枚举,您也可以轻松地、不需要太多仪式地创建一个 Bloom 过滤器,并与任何set实现相等比较。 - Pierre D
显示剩余3条评论

1

我无法想出一种常规使用起来不会太丑陋的完成它的方法。这是一个情况,在这种情况下,Python程序员必须在没有语言帮助的情况下小心处理数据类型。

只要记住你没用过那些会默默地在字符串和整数之间强制转换数据类型的语言,就应该心存感激了。


0
你可以定义一个函数来实现这个功能:
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

2
现在这不是对称的:isEqual(fooInstance, fooSubclassInstance)会抛出异常,但是isEqual(fooSubclassInstance, fooInstance)则不会。 - Jesse Rusak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接