简体   繁体   中英

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. 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 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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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