gpt4 book ai didi

python - 单语句异常检查

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:22 26 4
gpt4 key购买 nike

我只是好奇这是否存在。在编写 python 程序大半年之后,我从未遇到过它。

是否有一个 C 编译的 Python 函数(为了更快地访问推导式)来检查异常:

类似下面的函数:

def no_exception(function, *args, **kwargs):
try:
function(*args, **kwargs)
except Exception:
return False
return True

在这种情况下你可以使用它

# values is full of data
new_values = [float(n) if no_exception(float, n) else n for n in values]

最佳答案

至少标准库中没有。否则,Python unittest 模块中的 assertRaises 方法将使用它。请参阅:http://pythonhosted.org/gchecky/unittest-pysrc.html#TestCase.failUnlessRaises

您当然可以轻松编写自己的 C 实现。

关于python - 单语句异常检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com