简体   繁体   English

Python bool()函数可以为无效参数引发异常吗?

[英]Can the Python bool() function raise an exception for an invalid argument?

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. 如果参数无法转换为适当的数字类型,则int()float()等函数可能会引发异常( ValueError )。 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. 因此,通常很好的做法是将它们包含在try-except有可能将无效的参数传递给它们。

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. 但是,当涉及到“真实性”时,Python的灵活性,我想不出你可能传递给bool()函数的任何可能的值,这会引发异常。 Even if you call it with no argument at all, the function completes and returns False . 即使你完全没有参数调用它,该函数也会完成并返回False

Am I correct that bool() just won't raise an exception, as long as you pass it no more than one argument? 我是否正确bool()只是不会引发异常,只要你传递它不超过一个参数? And as a result, there's no point in enclosing the call in a try-except ? 结果,在try-except封闭电话是没有意义的吗?

bool complains when __bool__ does not return True or False . __bool__没有返回TrueFalse时, bool抱怨。

>>> 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 library has examples where bool will produce an error. DSM做了一个非常有价值的评论:流行的库有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 pointed out the following corner case. 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 . 标准的,近乎通用的stdlib示例,对于这样的事情:对死对象的weakref.proxy将引发几乎所有操作的ReferenceError,包括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) . 这不是bool独有的,任何使用其dead参数的函数都可能抛出此错误,例如myfunc = lambda x: print(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM