Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `if x:` completely equivalent to `if bool(x) is True:`?

Tags:

python

For a small testing framework we are writing I'm trying to provide some utility functions.

One of them is supposed to be equivalent to if x: but if that is completely equivallent to if bool(x) is True: then I could only provide one function to check if x is True: and if x:.

Is the negation of that also equivalent? if bool(x) is False: equal to if not x:?

like image 338
RedX Avatar asked Jul 21 '16 17:07

RedX


People also ask

What is correct data type of X if X true?

The truth value of all integers except 0 is true (in this case, the 2). if x == True: , however, compares x to the value of True , which is a kind of 1 .

How do you write if X is true in Python?

if you use if x ,it means it has to evaluate x for its truth value. But when you use x ==True or x is True . It means checking whether type(x)==bool and whether x is True.

How do I check if a value is true in Python?

You can check if a value is either truthy or falsy with the built-in bool() function. According to the Python Documentation, this function: Returns a Boolean value, i.e. one of True or False .

Is true a singleton in Python?

True and False are both singletons.


1 Answers

if x: is completely equivalent to testing for the boolean truth value, yes.

From the if statement documentation:

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section Boolean operations for the definition of true and false)

where the Boolean operations section details how truth is defined. The bool() function follows those exact same rules:

Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure.

The Standard Types documentation has a Truth Value Testing section:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

not simply inverts that same truth value; so if x is considered true by the above rules not x returns False, and True otherwise.

Be careful: in Python 2, the built-in names False and True can be masked by setting a global:

>>> True = False
>>> True
False

and thus is identity tests may be fooled by that re-assignment as well. Python 3 makes False and True keywords.

Your utility function should not need to use bool(x) is True or bool(x) is False. All you need is bool(x) and not bool(x), as these already produce True and False objects. bool() and not can't return anything else, using is True or is False on these is extremely redundant.

Last but not least, try not to re-invent the testing wheel. The Python standard library comes with a unittest library; it has both assertTrue and assertFalse functions, and the implementation of these functions just use if and if not.

like image 78
Martijn Pieters Avatar answered Sep 27 '22 17:09

Martijn Pieters