Lior Magen
Lior Magen

Reputation: 1573

How to figure if a variable is None, False or True while distinguishing between None and False

Let's say we have the following code which detects the stars rating of a document. If the stars rating is 50.0 it'll indicate it using stars_indicator = True and we would like to 'do something' in such case, if the stars rating is 10.0 it'll indicate it using stars_indicator = False and we would like to 'do something else' in this case.

stars_indicator = sentiment_indicator = None
if document[stars] == 50.:
   stars_indicator = True
elif document[stars] == 10.:
   stars_indicator = False

How can we check if we should 'do something' or 'do something else'?

Checking if it's True is simple

if stars_indicator:
   # do something

The trivial approach for checking if it's False or None will be

if not stars_indicator:
   # do something else

But in this way the if condition won't distinguish between the two options and will 'do something else' if stars_indicator False or None.

Upvotes: 2

Views: 4335

Answers (3)

NOhs
NOhs

Reputation: 2830

While others have answered how to check if your variable is True, False or None, I would like to point out that in your code snippet it would probably be easier if you just work without your stars_indicator:

if document[stars] == 50.:
    # Do what you would do if stars_indicator was True
elif document[stars] == 10.:
    # Do what you would do if stars_indicator was False
else:
    # Do what you would do if stars_indicator was None

In this way you do not need to encode your results in a variable just to then having to interpret your variable again. Of course this is all based on the code snippet you provided.

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599490

A much better way is to explicitly check for False or None with is:

if stars_indicator is None:

Upvotes: 11

Lior Magen
Lior Magen

Reputation: 1573

The right approach for this kind of problem is using isinstance()

if isinstance(stars_indicator, bool) and not stars_indicator:
   # do something else

isinstance(stars_indicator, bool) will first make sure that the variable is not None and only than will make sure that it's False.

This is an issue I had and wanted to share its solution.

Upvotes: -1

Related Questions