I’ve come across some code that reads:
if bool(x):
doSomething
I think that the following would do the same job:
if x:
doSomething
The reference says that it evaluates the suite if the test expression
is found to be true
The reference says of Boolean expressions:
In the context of Boolean operations, and also when expressions are used by control flow statements are used
by control flow statements, the following values are interpreted as
false: False, None, numeric zero of all types, and empty strings and
containers … All other values are interpreted as true.
The reference says of the bool() function:
Convert a value to a Boolean, using the standard truth testing procedure
So are the two above identical or is there some extra subtlety to it?
ifwill use__nonzero__()if available, as doesbool()when testing a value for truth. So yes, the behaviour is equivalent.From the documentation:
object.__nonzero__(self)