问题描述
如果参数不能为 int()
或 float()
等函数,则可能引发异常 (ValueError
)转换为适当的数字类型.因此,如果有可能将无效参数传递给它们,则将它们包含在 try-except
中通常是一种好习惯.
但由于 Python 在真实性"方面的灵活性,我想不出任何可能传递给 bool()
函数的值会引发异常.即使您完全不带参数调用它,该函数也会完成并返回 False
.
我是否纠正了 bool()
不会引发异常,只要您传递的参数不超过一个?因此,将调用包含在 try-except
中是没有意义的?
bool
在 __bool__
不返回 True
或 时报错错误
.
>>>类布尔失败:... def __bool__(self):...返回虚假"...>>>布尔(布尔失败())[...]TypeError: __bool__ 应该返回 bool,返回 str
不过,没有任何内置类型如此疯狂.
DSM 发表了非常有价值的评论:流行的 numpy 库中有 bool
会产生错误的示例.
>>>将 numpy 导入为 np>>>a = np.array([[1],[2]])>>>布尔(一)[...]ValueError:具有多个元素的数组的真值不明确.使用 a.any() 或 a.all()
user2357112 指出了以下极端情况.
<块引用>标准的、近乎通用的 stdlib 示例,例如:一个死对象的 weakref.proxy 将引发几乎所有操作的 ReferenceError,包括 bool
.
>>>导入弱引用>>>Foo类:... 经过...>>>bool(weakref.proxy(Foo()))[...]ReferenceError:弱引用对象不再存在
这不是 bool
独有的,任何使用其 dead 参数的函数都可能抛出此错误,例如 myfunc = lambda x: print(x)
.p>
It's possible for functions like int()
or float()
to raise an exception (ValueError
) if the argument can't be converted to the appropriate numeric type. Hence, it's generally good practice to enclose these in a try-except
if there's a possibility of an invalid argument being passed to them.
But with Python's flexibility when it comes to "truthiness," I can't think of any possible value you might pass to the bool()
function that would raise an exception. Even if you call it with no argument at all, the function completes and returns False
.
Am I correct that bool()
just won't raise an exception, as long as you pass it no more than one argument? And as a result, there's no point in enclosing the call in a try-except
?
bool
complains when __bool__
does not return True
or False
.
>>> class BoolFail:
... def __bool__(self):
... return 'bogus'
...
>>> bool(BoolFail())
[...]
TypeError: __bool__ should return bool, returned str
No builtin types are this insane, though.
DSM made a very valuable comment: the popular numpy library has examples where bool
will produce an error.
>>> import numpy as np
>>> a = np.array([[1],[2]])
>>> bool(a)
[...]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
user2357112 pointed out the following corner case.
Standard, near-universal stdlib example for things like this: a weakref.proxy to a dead object will raise a ReferenceError for almost any operation, including
bool
.
>>> import weakref
>>> class Foo:
... pass
...
>>> bool(weakref.proxy(Foo()))
[...]
ReferenceError: weakly-referenced object no longer exists
This is not unique to bool
, any function that uses its dead argument might throw this error, for example myfunc = lambda x: print(x)
.
这篇关于Python bool() 函数能否为无效参数引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!