python - 检查两个对象是否可以相互比较,而不依赖于引发的错误

标签 python comparison-operators

“可比较”是指“能够相互执行比较操作 ><>=<===!= 而无需引发 TypeError ”。此属性确实适用于许多不同的类:

1 < 2.5  # int and float
2 < decimal.Decimal(4)  # int and Decimal
"alice" < "bob"  # str and str
(1, 2) < (3, 4)  # tuple and tuple

但它没有:

1 < "2"  # int and str
1.5 < "2.5"  # float and str

即使看起来确实应该:

datetime.date(2018, 9, 25) < datetime.datetime(2019, 1, 31)  # date and datetime 
[1, 2] < (3, 4)  # list and tuple

As demonstrated in this similar question ,您显然可以检查两个未知类型的对象 ab通过使用传统的Python方法“请求宽恕,而不是许可”并使用 try/except block :

try: 
    a < b
    # do something
except TypeError:
    # do something else

但是catching exceptions is expensive ,并且我希望第二个分支能够足够频繁地被采用,因此这一点很重要,所以我想在 if 中捕捉到这一点。/else代替声明。我该怎么做?

最佳答案

由于在实际执行此类操作之前不可能事先知道是否可以对两种特定类型的操作数执行比较操作,因此您可以做的最接近的事情是实现避免捕获 TypeError是缓存之前已经引起TypeError的已知运算符组合以及左右操作数的类型。您可以通过创建一个具有此类缓存和包装方法的类来完成此操作,这些方法在继续比较之前执行此类验证:

from operator import gt, lt, ge, le

def validate_operation(op):
    def wrapper(cls, a, b):
        # the signature can also be just (type(a), type(b)) if you don't care about op
        signature = op, type(a), type(b)
        if signature not in cls.incomparables:
            try:
                return op(a, b)
            except TypeError:
                cls.incomparables.add(signature)
        else:
            print('Exception avoided for {}'.format(signature)) # for debug only
    return wrapper

class compare:
    incomparables = set()

for op in gt, lt, ge, le:
    setattr(compare, op.__name__, classmethod(validate_operation(op)))

这样:

import datetime
print(compare.gt(1, 2.0))
print(compare.gt(1, "a"))
print(compare.gt(2, 'b'))
print(compare.lt(datetime.date(2018, 9, 25), datetime.datetime(2019, 1, 31)))
print(compare.lt(datetime.date(2019, 9, 25), datetime.datetime(2020, 1, 31)))

将输出:

False
None
Exception avoided for (<built-in function gt>, <class 'int'>, <class 'str'>)
None
None
Exception avoided for (<built-in function lt>, <class 'datetime.date'>, <class 'datetime.datetime'>)
None

这样您就可以使用 if 语句而不是异常处理程序来验证比较:

result = compare.gt(obj1, obj2)
if result is None:
    # handle the fact that we cannot perform the > operation on obj1 and obj2
elsif result:
    # obj1 is greater than obj2
else:
    # obj1 is not greater than obj2

以下是一些时间统计数据:

from timeit import timeit
print(timeit('''try:
    1 > 1
except TypeError:
    pass''', globals=globals()))
print(timeit('''try:
    1 > "a"
except TypeError:
    pass''', globals=globals()))
print(timeit('compare.gt(1, "a")', globals=globals()))

在我的机器上输出:

0.047088712933431365
0.7171912713398885
0.46406612257995117

正如您所看到的,当比较抛出异常时,缓存的比较验证确实可以为您节省大约 1/3 的时间,但当比较没有抛出异常时,速度会慢 10 倍左右,因此只有在您预期时,这种缓存机制才有意义绝大多数的比较都会抛出异常。

关于python - 检查两个对象是否可以相互比较,而不依赖于引发的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57717100/

相关文章:

php - 如何在我的网站上显示我的Facebook Wall

python - 如何判断 python 的 ZipFile.writestr() 是否因为文件已满而失败?

不使用比较运算符比较两个数字

python - 我如何使这么长的 if 语句不那么麻烦?

c++ - 比较 C++20 中的多态类型

python依赖+部署工具?

python - 如何打开(两次)使用 tempfile.NamedTemporaryFile() 创建的文件

python - 多线程和多处理线程池之间的区别?

c++ - 您可以将 nullptr 与其他指针进行比较以进行排序吗?它总是更小吗?