Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 241
JDM Avatar asked Oct 17 '18 19:10

JDM


People also ask

What does bool () do in Python?

The bool() function returns the boolean value of a specified object.

How do you raise an exception error in Python?

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.

What does bool (' false ') return?

It returns False if the parameter or value passed is False.


1 Answers

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

like image 50
timgeb Avatar answered Sep 19 '22 13:09

timgeb