Python bool() 函数可以为无效参数引发异常吗?
Can the Python bool() function raise an exception for an invalid argument?
如果参数无法转换为适当的数字类型,int()
或 float()
等函数可能会引发异常 (ValueError
)。因此,如果有可能将无效参数传递给它们,将它们括在 try-except
中通常是一种很好的做法。
但是考虑到 Python 在 "truthiness," 方面的灵活性,我想不出任何可能传递给 bool()
函数的值会引发异常。即使您根本不带任何参数调用它,该函数也会完成并且 returns False
.
我是否正确认为 bool()
不会引发异常,只要您传递给它的参数不超过一个?因此,将调用包含在 try-except
?
中毫无意义
bool
抱怨 __bool__
不 return True
或 False
.
>>> class BoolFail:
... def __bool__(self):
... return 'bogus'
...
>>> bool(BoolFail())
[...]
TypeError: __bool__ should return bool, returned str
虽然没有内置类型如此疯狂。
DSM made a very valuable comment: the popular numpy 库有示例,其中 bool
会产生错误。
>>> 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 指出了以下极端情况。
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
这不是 bool
独有的,任何使用其死参数的函数都可能抛出此错误,例如 myfunc = lambda x: print(x)
.
如果参数无法转换为适当的数字类型,int()
或 float()
等函数可能会引发异常 (ValueError
)。因此,如果有可能将无效参数传递给它们,将它们括在 try-except
中通常是一种很好的做法。
但是考虑到 Python 在 "truthiness," 方面的灵活性,我想不出任何可能传递给 bool()
函数的值会引发异常。即使您根本不带任何参数调用它,该函数也会完成并且 returns False
.
我是否正确认为 bool()
不会引发异常,只要您传递给它的参数不超过一个?因此,将调用包含在 try-except
?
bool
抱怨 __bool__
不 return True
或 False
.
>>> class BoolFail:
... def __bool__(self):
... return 'bogus'
...
>>> bool(BoolFail())
[...]
TypeError: __bool__ should return bool, returned str
虽然没有内置类型如此疯狂。
DSM made a very valuable comment: the popular numpy 库有示例,其中 bool
会产生错误。
>>> 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 指出了以下极端情况。
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
这不是 bool
独有的,任何使用其死参数的函数都可能抛出此错误,例如 myfunc = lambda x: print(x)
.