Python bool()函数是否可以为无效参数引发异常? [英] Can the Python bool() function raise an exception for an invalid argument?
问题描述
int()
或 float()
之类的函数可能会引发异常( ValueError
),如果参数不能转换为适当的数字类型。因此,通常最好将它们包含在 try-except
中,如果有可能将无效的参数传递给它们。
但是由于Python在真实性方面的灵活性,我想不出您可能会传递给 bool()
函数的任何可能的值提出一个例外。即使您根本不带任何参数调用它,该函数也会完成并返回 False
。
我更正了 bool()
不会引发异常,只要您传递不超过一个参数即可?结果,将呼叫括在 try-except
?
bool
抱怨 __ bool __
不返回 True
或 False
。
>> class BoolFail:
... def __bool __(自己):
...返回假
...
>>> bool(BoolFail())
[...]
TypeError:__bool__应该返回bool,返回str
但是,没有内置类型如此疯狂。
DSM 发表了非常有价值的评论:流行的 numpy 库中有示例,其中 bool
会产生错误。
>>>将numpy导入为np
>> a = np.array([[1],[2]])
>> bool(a)
[...]
ValueError:具有多个元素的数组的真值不明确。使用a.any()或a.all()
user2357112 指出了以下几种极端情况。
标准,几乎通用stdlib示例就是这样:对死对象的weakref.proxy将对几乎所有操作(包括
bool
。
$>)引发ReferenceError。 blockquote>
>> importweakref
>> Foo类:
...通过
...
>> bool(weakref.proxy(Foo()))
[...]
ReferenceError:弱引用对象不再存在
这不是
bool
所独有的,任何使用其dead参数的函数都可能抛出此错误,例如myfunc = lambda x:print(x)
。It's possible for functions like
int()
orfloat()
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 atry-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 returnsFalse
.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 atry-except
?解决方案
bool
complains when__bool__
does not returnTrue
orFalse
.>>> 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 examplemyfunc = lambda x: print(x)
.这篇关于Python bool()函数是否可以为无效参数引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!