5

I have a boolean variable named mapped_filter. If I am not wrong, this variable can hold 3 values, either True, False or None.

I want to differentiate each of the 3 possible values in an if statement. Is there a better way to achieve that than doing the following?

if mapped_filter:
    print("True")
elif mapped_filter == False:
    print("False")
else:
    print("None")
3
  • 4
    if mapped_filter is None unmistakably compares with None... Commented Mar 12, 2018 at 12:49
  • if you're looking for a case statement, I'm sorry, but no, there's not a better way. You still can do crazy things like having a dictionary like crazy_dict = {True: ..., False:..., None: ...} and then crazy_dict[mapped_filter](). Commented Mar 12, 2018 at 12:52
  • 4
    Your assumption is wrong. If mapped_filter is a boolean, it can only have two different values: True or False. Commented Mar 12, 2018 at 12:52

1 Answer 1

11

In your code anything that's not truthy or False prints "None", even if it's something else. So [] would go print None. If no object other than True, False and None can get there your code is fine.

But in python we generally allow any object to be truthy or not. If you want to do this, a better way would be to do:

if mapped_filter is None:
    # None stuff
elif mapped_filter:
    # truthy stuff
else:
    # falsey stuff

if you explicitly want to disallow any value that's not a bool or None, then instead do:

if isinstance(mapped_filter, bool):
    if mapped_filter:
        # true stuff
    else:
        # false stuff
elif mapped_filter is None:
    # None stuff
else:
    raise TypeError(f'mapped_filter should be None or a bool, not {mapped_filter.__class__.__name__}')
Sign up to request clarification or add additional context in comments.

1 Comment

That was what I was looking to. This approach looks better. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.