[英]Does python have a “causes_exception()” function?
I have the following code: 我有以下代码:
def causes_exception(lamb):
try:
lamb()
return False
except:
return True
I was wondering if it came already in any built-in library? 我想知道它是否已经在任何内置库中了?
/YGA / YGA
Edit: Thx for all the commentary. 编辑:Thx为所有评论。 It's actually impossible to detect whether code causes an exception without running it -- otherwise you could solve the halting problem (raise an exception if the program halts). 实际上不可能在不运行代码的情况下检测代码是否会导致异常-否则您可以解决停止问题(如果程序停止则引发异常)。 I just wanted a syntactically clean way to filter a set of identifiers for those where the code didn't except. 我只是想用一种语法上干净的方法来过滤代码中没有的那些标识符集。
No, as far as I know there is no such function in the standard library. 不,据我所知,标准库中没有此类功能。 How would it be useful? 有什么用? I mean, presumably you would use it like this: 我的意思是,大概您会这样使用它:
if causes_exception(func):
# do something
else:
# do something else
But instead, you could just do 但是相反,你可以做
try:
func()
except SomeException:
# do something else
else:
# do something
There's assertRaises(exception, callable)
in unittest
module and this is probably the only place where such check makes sense. unittest
模块中有assertRaises(exception, callable)
,这可能是唯一可以进行这种检查的地方。
In regular code you can never be 100% sure that causes_exception
you suggested are not causing any side effects. 在常规代码中,您永远不能百分百确定您建议的causes_exception
不会引起任何副作用。
I'm not aware of that function, or anything similar, in the Python standard library. 我不了解Python标准库中的该功能或类似功能。
It's rather misleading - if I saw it used, I might think it told you without calling the function whether the function could raise an exception. 这颇具误导性-如果我看到它使用过,我可能会认为它告诉您而没有调用该函数是否会引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.