Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the correct way to check for False? [duplicate]

Which is better? (and why?)

if somevalue == False:

or

if somevalue is False:

Does your answer change if somevalue is a string?

like image 651
patchwork Avatar asked May 08 '16 19:05

patchwork


People also ask

How do you check for false 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 .

How do you check boolean in Python?

We can evaluate values and variables using the Python bool() function. This method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.


1 Answers

It rather depends on what somevalue can be: if somevalue could be anything you could check that it's a boolean and not:

if isinstance(somevalue, bool) and not somevalue

this doesn't rely on False being a singleton. If it always is a singleton you can also do:

if somevalue is False

But PEP8 of Python states you shouldn't care if it about the class and just use:

if not somevalue

this will evaluate if somevalue is "falsy". See Python documentation on Truth value testing.

PEP8 states:

Don't compare boolean values to True or False using == .

and gives these examples:

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

which translates in your case to:

Yes:   if not greeting:
No:    if greeting == False:
Worse: if greeting is False:

Keep in mind that each string is considered "truthy" except the empty string ''.

like image 74
MSeifert Avatar answered Oct 23 '22 17:10

MSeifert