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
?
The bool() function returns the boolean value of a specified object.
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
It returns False if the parameter or value passed is False.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With